Javascript audio isn't working on mobile devices

放肆的年华 提交于 2021-02-08 11:32:36

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!