Mp3 single play on web page with JavaScript and Cookies

As in my prior post, I had another web site that played media every time someone entered the site,  but this time it was an MP3 file playing using a HTML5 audio player.

So, I adapted the script developed for the YouTube single play purpose to the mp3 HTML5 purpose stated above. I won’t go into specifics since all of that is covered in that article. If you have need for a script like this to limit playback of an mp3 file to once every hour on visiting a page then grab this code and make it work! Enjoy!

<audio controls id=”audioframe” autoplay=””>
<source src=”/audio/somefile.mp3
type=”audio/mpeg”>Your browser does not support the audio element.

<script language=”javascript”>
// Autoplay on first load and then expire in one hour on cookie.
// Author: J.F. Almada

// Set the video to play here
var autoplay = “”;
var now = new Date();
var time = now.getTime();
// Expire the cookie in one hour
var expireTime = time + 1000*3600;

if (document.cookie.length == 0 || document.cookie.indexOf(“AUDIOCOOKIENAMEHERE=”) == -1) {
// Set the expiration
// Set the cookie with it’s autoexpiration
document.cookie = ‘AUDIOCOOKIENAMEHERE=true;expires=’+now.toGMTString()+’;path=/’;

autoplay += ‘autoplay’; // append an autoplay tag to the video URL
// For debugging – Uncomment to view the setting
// alert(autoplay);

// Pass the link value to the Iframe
document.getElementById(“audioframe”).autoplay = autoplay; // set the iframe autoplay