1

I want to play html5 audio player to play the same audio without any delay even if I go to the next page.. It's working with cookie.. But the problem is..whenever I reload the page the player starts playing on it's own..I know it's very tough to stop this..since it's calling the update() function automatically..but any help would be great.. I want the player not to play anything on page load...but if I play something and move on to the next page it will fetch cookie and play it.. Here's my code.. :

<a href="index.php">Index</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<a href="next.php">Next</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<audio controls preload="auto"  autobuffer >
<source src="example.mp3" type="audio/mpeg" />
Your browser does not support the audio element.
</audio>



<script>

function setCookie(c_name,value,exdays)
{
    var exdate=new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
    document.cookie=c_name + "=" + c_value;
}

function getCookie(c_name)
{
    var i,x,y,ARRcookies=document.cookie.split(";");
    for (i=0;i<ARRcookies.length;i++)
    {
      x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
      y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
      x=x.replace(/^\s+|\s+$/g,"");
      if (x==c_name)
        {
        return unescape(y);
        }
      }
}

var song = document.getElementsByTagName('audio')[0];

var played = false;
var tillPlayed = getCookie('timePlayed');


function update()
{
    if(!played){
        if(tillPlayed){
        song.currentTime = tillPlayed;
        song.play();
        played = true;
        }
        else {
                song.play();
                played = true;
        }
    }

    else {
    setCookie('timePlayed', song.currentTime);
    }
}
setInterval(update,0);
</script>
Christian Phillips
  • 18,399
  • 8
  • 53
  • 82
user2605321
  • 93
  • 2
  • 5
  • 11

1 Answers1

0

You're constantly writing the cookie. If I were you, I just write it in a page exit event: window.onbeforeunload = function (e) { setCookie('timePlayed', song.currentTime); }

If your cookie is well written and read (check with console.logs or alerts) then the problem has to be with the audio function.