2

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.

Chris Christensen
  • 192
  • 1
  • 2
  • 18
  • Someone suggested using the `touchstart` event instead of `click`. I haven't tested it so I'm not sure that will help. http://stackoverflow.com/questions/9419386/how-to-play-sounds-in-javascript#11703690 – showdev Apr 10 '13 at 23:06

2 Answers2

2

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>
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • 1
    Thanks for the reply. I tried replacing the portion of the code with this but it didn't work. I got an ILLEGAL on it. Is it possible to put an audio tag inside of a function like so? – Chris Christensen Apr 11 '13 at 13:40
  • Yes, if you escape it right. But really you'd be better off using `var aud = document.createElement('audio')`, then you can test `aud.canPlayType("audio/mpeg")` to check for MP3 support. It's a lot tidier! – Niet the Dark Absol Apr 11 '13 at 13:44
  • Does the var aud = document.createElement('audio') replace the document.getElementById('sound').innerHTML portion of the code or does it replace the " – Chris Christensen Apr 11 '13 at 15:54
  • I think I have figured out most of this. I changed it so that I'm using `document.createElement('audio')` and learned quite a bit about it on the w3schools site and the Mozilla developer site. Thanks again for the help. – Chris Christensen Apr 12 '13 at 13:32
0

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

Unome
  • 6,750
  • 7
  • 45
  • 87