问题
The code below works fine on desktop browsers (plays music). But when I try to open the site on any mobile device it doesn't work.
var music = new Audio("mscs/gamemusic.mp3");
function playmusic() {
music.controls = false;
music.loop = false;
music.autoplay = true;
document.body.appendChild(music)
}
I use it in a function when game starts:
function createnewgame() {
...
playmusic();
...
...
}
Does anyone know what's wrong?
回答1:
Well, this is clearly a browser support issue. According to caniuse, the <audio>
element (and js' Audio
object is an interface used for it) has known support issues, including
iOS and Chrome on Android do not support
autoplay
as advised by the specification
and others. Not sure if this can be overcome by some library but since the limitation of autoplay
was introduced by design, I wouldn't count on workarounds...
回答2:
Instead of adding the var "music" to html body, you can try playing the audio directly from JavaScript.
function playmusic() {
music.play();
}
回答3:
Some mobile browsers support automatic playback of audio, but ios, chrome and others require interactive actions to trigger the sound playback.You can try working with the mute attribute...enter link description here
来源:https://stackoverflow.com/questions/52140952/javascript-audio-isnt-working-on-mobile-devices