If I refresh a URL audio playing works but for the next time onwards its not playing(its playing randomly). I used phaser framework with Javascript.
Here is my code:
function OtpAudio(product)
{
game.load.audio('theme',
['../../../product_assets/'+product+'/audio/eng/OTP.mp3'
]);
var music = game.sound.add('theme');
music.play();
console.log(music);
}
I am trying to call the above function multiple times but it works only for the first time as I mentioned. Please help me on this.
game.sound.add('theme', { loop: true });
You can use the above code if you want to play music in a loop.
I asume the first time the music plays is after clicking a link or so. And It doesn't play when you reload the site.
The reason is that, browser prevent playing audio without user interaction.
If you check the browser console you can see an error like:
DOMException: play() failed because the user didn't interact with the document first. ...
To prevent this you can check in the create function if this.sound.locked==true, this would mean sound cannot be played, and than you can prompt the user to click/touch/interact/... with the browser, and on the next interaction you start the sound.
Details to the sound locked documentation: https://photonstorm.github.io/phaser3-docs/Phaser.Sound.WebAudioSoundManager.html#locked__anchor
An alternative simpler approach would be to check on any user event, if the audio is playing. importaint check if music.isPlaying == false and this.sound.locked==false and if both match you can call music.play() the music.