rksh rksh - 2 years ago 71
HTML Question

HTML audio element not playing on first time?

I'm using the html audio element in one of my projects where I load the src of the element dynamically using VueJS once the play button is pressed.

Everything seems to work fine, but when I press the button on the first time the audio doesn't play. I have to click the play button a second time to make it start playing. How can I fix this?

I even checked whether the src is there before playing by using console.log(element) which shows the audio with the SRC.

But it is not playing in the first attempt.

My code looks like this.

var player = document.getElementById('player');
if(player.src != ""){

How can I fix this? Thanks. It's very annoying.

Answer Source

This should help

var player= document.getElementById('player');

player.addEventListener('canplaythrough', function() { 
}, false);

Also make sure is event triggered when you press the button.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download