0

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?

YakovL
  • 7,557
  • 12
  • 62
  • 102
  • have you put an `alert` inside `playmusic` to check whether the function is actually called on mobile devices? I also recommend you to list mobile OSes and browsers you have tried. – YakovL Sep 02 '18 at 23:03
  • @YakovL Yes I tried alert message and it appears but still music doesn't play. – Devrim Torgul Sep 02 '18 at 23:27

3 Answers3

0

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...

YakovL
  • 7,557
  • 12
  • 62
  • 102
0

Instead of adding the var "music" to html body, you can try playing the audio directly from JavaScript.

function playmusic() {
music.play();
}

0

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

Max
  • 21
  • 1
  • 8
  • I don't understand... I want to play audio when the game opens. I could not understand the mute attribute... – Devrim Torgul Sep 04 '18 at 18:55
  • It doesn't work if you want a web page to play sound as soon as it enters the mobile browser.Some browsers require user interaction.Two Suggestions were made.One is to play the sound when the user touches the screen, and the other is to display the mute icon on the page when the user enters the page, indicating that the page is silent at this time. – Max Sep 05 '18 at 02:14