Search code examples
javascriptaudioalertinnerhtmlisset

Javascript:: audio.currentTime is updated properly only after alert


I think that I found a bug on JavaScript Audio API.

My code is working perfectly like that :

var audio=new Audio();
var lastPause;

var myPlayer=document.querySelector('#player>.button.hand');
var playerStatus=("textContent" in document)?"textContent":"innerText";

myPlayer.addEventListener
(
    'click',
    function()
    {

        if(audio.paused)
        {

            audio.src="Nadav Guedj - Golden Boy (Eurovision 2015 - Israel - Karaoke).mp3";
            myPlayer.innerHTML="►";           

            if(lastPause)
            {
                alert(lastPause); //If I remove this line it's not working when lastPause is defined!
                audio.currentTime=lastPause;
            }

            audio.play();

        }
        else
        {
            myPlayer.innerHTML="||";
            lastPause=audio.currentTime;
            audio.pause();
        }

    }

);

BUT

If I remove or remark the alert line alert(lastPause); the audio stuck when lastPause is defined or iow... The second time the user press play (after pause).


Solution

  • I am assuming this question is related to this question my answer there is applicable for this also,

    repeated setting audio.src is your problem. you have two ways of fixing this:

    • get rid of audio.src line, bunch of other redundant code could also be removed with it.
    • the reason it works when you use alert is, when alert is triggered, the next few lines are not executed till you dismiss it, in these precious few seconds/ milliseconds, the audio element whose source has been changed has enough time to load the new metadata, only then can the current time can be set. so you can modify the code to trigger setting of audio on metadata loading:

      ...
      myPlayer.innerHTML="►";           
      audio.play();
      audio.onloadedmetadata = function(){
          if(lastPause){
              audio.currentTime = lastPause;
          }
      };
      

    fiddle demo