Chris Christensen
Chris Christensen

Reputation: 302

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.

Upvotes: 3

Views: 2119

Answers (2)

Unome
Unome

Reputation: 6900

Unfortunately, iOS locks the audio/video objects to 1 per web page, so once you get that one loaded, you've used your one. This will silently kill all your other sound files you want to play at the same time. I've struggled for several weeks to get multi-track audio to work in iOS via javascript and the best solution so far that has worked for me is the Web Audio API. I've attached a tutorial for you, hopefully it'll be useful

Upvotes: 0

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324790

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>

Upvotes: 2

Related Questions