Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
I have an audio clip that plays via the EMBED tag on a webpage. Here's the code:
<EMBED SRC="audio/message.mp3" AUTOSTART="true" VOLUME="50" HEIGHT="60" WIDTH="144" HIDDEN="TRUE">
It play once and stops, which is what I want, however, if a visitor goes to another page in the site, then returns to the audio-embedded page, the sound plays again. Is there any way to play the sound only once per visit to the site? Perhaps by using a cookie? Thanks!

Yes and no. If you only want the clip to play once during a visit to the page, then what you want to use is session variables. You would need to have some type of back-end support on the web server (such as PHP or VBScript) to accomplish this - at least I don't think you can do it with client-side JavaScript.
You could use cookies to limit the clip from playing for specified time periods though. For example, the page checks to see if the cookie has been set. If the cookie has not been set (or if it was set more than 24 hours ago) it plays the clip and set a cookie. If your server supports a back-end scripting language, such as PHP or VBScript, that would still be the best approach for this method as well. However, if you don't have that cabability you can still do this with client-side JavaScript
Michael J

I like the cookie approach because it seems less complicated. Besides, my visitors won't be spending a ton of time on the site, so if I could set a cookie that indicates whether or not the sound has been played in the last hour, that would be fine. I don't suppose you'd be willing to share an example of such code with me? I'm no JavaScript expert, heck, I'm not even a JavaScript beginner, so I sure would appreciate any help you can give me. Thanks.

Here is a page with JavaScript functions that allow you to set, read and delete cookies. Include that code in the head of your page.
Then where you would put the EMBED tag do this (I have not tested it):
<script language="javascript">
if (!getCookie('lastClip')) {
//Include the clip
document.write('<EMBED SRC="audio/message.mp3" AUTOSTART="true" VOLUME="50" HEIGHT="60" WIDTH="144" HIDDEN="TRUE">')
setCookie('lastClip',true,3600000)
}
</script>The number above in red is the time (in milliseconds) for the cookie to expire. The time I put there is for 1 hour (1000ms * 60sec * 60min). Change it for whaever amount of time you want.
I also ran across some examples concerning session cookies for javascript. That would probably be an even berrter handling of this.
http://www.javascriptkit.com/javatutors/cookie.shtml
Michael J

![]() |
![]() |
![]() |

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |