Search code examples
javascriptioshtmlipadmobile-safari

Javascript audio plays in browser but not on iOS device


I have the following code for playing an audio file from an array

function playSound() {
    if(index>=25){
        index = 0;
}
document.getElementById("sound").innerHTML=
"<embed src=\""+audio[index]+"\" hidden=\"true\" autostart=\"true\" loop=\"false\" />";
index++;
}

The audio plays fine on my laptop but won't play on the iOS device. The code is triggered from the following HTML

<button id="newWordBtn" class="play" onclick="playSound(); $('#result').empty(); $('#yourTurn').val(''); myFunction();" data-icon="refresh" tabindex="3">New Word</button>

Any ideas on how I can get this working? I know that iOS doesn't allow autoplay but this sound is triggered by a button.


Solution

  • Many mobile browsers do not handle <embed> tags. Also, you don't show what the sources are, but I'm going to bet you're using a MP3 file - this is fine for browsers that support MP3, but for those that don't... yeah.

    You should end up with something like this:

    <audio autostart>
        <source type="audio/ogg" src="mySong.ogg" />
        <source type="audio/mpeg" src="mySong.mp3" />
        <p>Your browser does not support HTML5 audio. Sorry!</p>
    </audio>