简体   繁体   中英

javascript add background audio to game

I am attempting to add a mp3 file to my game menu, but I cannot get it to play unless I use controls and physically have to press the play button on the browser next to the game canvas.

I have been to several websites and tutorials, as I know this is a common question, but I cannot seem to get it to work.

So far I have tried adding

const audioObj = new Audio("/assets/menuTheme.mp3");

audioObj.play();

to my game.js file in the update function, but that didn't work.

I have added the to my html file in multiple ways such as:

<audio id= 'menuAudio'>
<source src='/assets/menuTheme.mp3'>
</audio>

and

<audio controls autoplay loop>
<source id = 'menuAudio' src='/assets/menuTheme.mp3'/>
<embed src= '/assets/menuTheme.mp3' autoplay='autoplay' loop='loop'/>
</audio>

then calling it in my game.js file by

this.sound = document.getElementById('menuAudio');
this.sound.play();

I even found one answer to create a function or a class for the sound

sound = function(src) {
this.sound = document.createElement('audio');
this.sound.src = src;
this.sound.setAttribute('preload', 'auto');
this.sound.setAttribute('controls', 'none');
this.sound.style.display = 'none';
document.body.appendChild(this.sound);
this.play = function() {
    this.sound.play();
}
this.stop = function() {
    this.sound.pause();
}
}

Nothing has worked, and I am stumped on what else to do. I know the file is supported by the browser I am using and is uploaded properly, because it will play, just not automatically, and not without having the control panel showing.

Please help:)

SOLVED:

always check if auto-play is enabled in the browser...* face-to-palm *

check if the audio is paused first, then play it if it returns true.. also this must happened inside a window.onload event

if(audio.isPaused)
   audio.play()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM