Playing Sounds in Phonegap on iOS


I’ve worked out that iOS is pretty funny about sounds, especially as it turns out Safari makes it very difficult to play them automatically, thus saving on users’ precious data usage plans (never mind the fact that my sound effects are already downloaded onto the device and are smaller than your average jpeg anyway!). It’ll do it in response to a user action, but that’s such a woolly and undefined concept that I had to fiddle around for a while.

I didn’t have any luck using the usual Phonegap methods. Well I did but it only worked when headphones were plugged in, for some reason, and I eventually gave that up as a dead end. It appeared to play the sound, firing onSuccess callbacks and such, but I couldn’t hear anything, thus rather defeating the point of the exercise.

Anyway, here’s an example of what didn’t work for me, followed by one that did. Hope it’ll save you some silly bother.

Doesn’t work:

var myAudio = new Media('sounds/mySoundFile.wav');
myAudio.play();

Works:

<audio src='sounds/mySoundFile.wav' id='sound'>
<button id='myButton' onClick='document.getElementById("sound").play()'>

If like me you prefer jQuery to the monstrosity we like to call raw Javascript, it would appear that inside your click() function you’ll need to use $(‘#sound’)[0].play() rather than $(‘#sound’).play(). I think that’s because then you escape the jQuery-ness and call the DOM’s native play() method on the <audio> element itself, not some set of jQuery-enhanced elements.

So, that was nice and straightforward, thanks Apple!!! In case you can’t tell, I’m being sarcastic :P

 

, , , , ,

  1. #1 by lucas on 27 January, 2012 - 1:08 am

    Thanks for the tip. I am wondering if you can record audio using media class and save it in a specific folder such as ‘www/audio/’?

  2. #2 by George Nixon on 27 January, 2012 - 12:36 pm

    I’m afraid I have no idea, Lucas, sorry! Perhaps a fellow visitor to the site could advise.. Anyone?

    You could try Phonegap’s forums too :)

(will not be published)