First of all: Support for HTML5 audio in Mobile Safari on iOS (5.01, 5.1) is quite limited . But I managed to get some small sounds, such as events, that work in my iPad 2 IP applications. Since you are talking about only one audio file for your application, you do not need to return to the tricks of audio sprites (for example, merging several MP3s into one MP3 file and changing the playback position in the combined file depending on the sound you want to play).
As you noticed, you cannot automatically play audio in Mobile Safari, i.e. without the user clicking an item. Technically speaking, sound should be played (not loaded) in the same call stack as the click event. But you are likely to experience a delay of 0.5 seconds when Mobile Safari creates an audio object. Here is the solution to this "problem":
- At the beginning of your application (during loading / initialization) add a click handler to the HTML document that will start playing your audio file as soon as the user clicks / writes anywhere in the application. This will cause Safari to start loading the sound.
- Listen to the play event, which fires when the sound is ready to play and pauses immediately.
- Now start playing the sound (without delay) again when you need it.
Here is a little JavaScript code:
function initAudio() { var audio = new Audio('./path/to/my/sound.mp3'); audio.addEventListener('play', function () { // When the audio is ready to play, immediately pause. audio.pause(); audio.removeEventListener('play', arguments.callee, false); }, false); document.addEventListener('click', function () { // Start playing audio when the user clicks anywhere on the page, // to force Mobile Safari to load the audio. document.removeEventListener('click', arguments.callee, false); audio.play(); }, false); }
source share