rksh
rksh

Reputation: 4050

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.

Upvotes: 4

Views: 2742

Answers (1)

Ruben  Yeghikyan
Ruben Yeghikyan

Reputation: 497

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.

Upvotes: 4

Related Questions