Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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');
console.log(player)
if(player.src != ""){
    player.play();
};

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

like image 683
rksh Avatar asked Nov 04 '25 22:11

rksh


1 Answers

This should help

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

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

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

like image 137
Ruben Yeghikyan Avatar answered Nov 07 '25 18:11

Ruben Yeghikyan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!