Sagar Hugar
Sagar Hugar

Reputation: 31

Error while playing Audio in browser

I am playing audio with user specified starttime using javascript code

var audio_player = document.getElementById("audi");
//'audi' is ID of audio tag  
audio_player.currentTime = audi_start_time;
//Start time from where audio should start to play

audio_player.play();

when I run website I'm able to play the audio from the time specified in 'audi_start_time' but most of the time I'm getting error

'An attempt was made to use an object that is not, or is no longer, usable
[Break On This Error]

audio_player.currentTime = audi_start_time;

Any help would be appreciated. thanks in advance

Upvotes: 2

Views: 2407

Answers (2)

TheJeff
TheJeff

Reputation: 4101

Play the audio before you set current time. I beat my head on the desk all night over this, and then I found this thread: https://github.com/johndyer/mediaelement/issues/243. This ended up working for me:

audioplayer.src = source;
audioplayer.play();
audioplayer.addEventListener('playing', function () {
    if (loadPlayed == false)
    {
        audioplayer.currentTime = Time;
        audioplayer.play();
        loadPlayed = true;
    }
    else {
        audioplayer.removeEventListener('playing', this);
    }
}); 

Upvotes: 0

Okan Kocyigit
Okan Kocyigit

Reputation: 13421

I think you are trying to set currentTime before document ready,

because it's working when you set currentTime in window.onlaoad.

here is what you are trying to do -> jsFiddle demo-1 (not working)

here is what you should do -> jsFiddle demo-2 (working)


EDIT:

Ok, I got it. If you are trying to set currentTime of audio/video tag that appended dynamically, you should wait for audio tag to be ready to play.

So you can detect it with oncanplay event,

for example,

<div id="content"></div>
<button onclick="play()">play</button>

<script type="text/javascript">
function play() {
     var audio = document.createElement("audio");
     audio.controls = "controls";
     audio.innerHTML = '<source src="http://www.w3schools.com/html5/song.ogg" type="audio/ogg" />'+
                       '<source src="http://www.w3schools.com/html5/song.mp3" type="audio/mp3" />';
     var content = document.getElementById("content");
     content.innerHTML = "";
     content.appendChild(audio);
     audio.addEventListener("canplay", function() {
        this.currentTime = 5;        
     },true);
     audio.play();
}
</script>​

and here is a working jsFiddle demo

Upvotes: 2

Related Questions