Getting Safari to play a short audio clip with HTML5's audio tag

Alec Jacobson

August 19, 2011

weblog/

I had a really annoying time trying to get Safari to load and play a small audio clip (mp3) I'd posted. The clip is only 2 seconds. Here's the HTML I was using
<audio src="audio.mp3" autoplay preload="auto" controls loop>
But this resulting in nothing. Upon closer inspection I found out the the "onstalled" even was being fired so I added an "onstalled" even handler to try to load the clip again:
<audio onstalled="this.load();" src="audio.mp3" autoplay preload="auto" controls loop>
But this was to no avail, the "onstalled" event just fired each time recursively. In the end I gave up on Safari's ability to play/load small mp3 files. I'm not sure what the problem is since quicktime played the file fine. Also if my html and audio.mp3 files lived locally, Safari played it correctly. I instead made use of HTML5 ability to specify fallback sources. For this I converted my mp3 file to a m4a: First convert to wav with mplayer:
mplayer -quiet -vo null -vc dummy -ao pcm:waveheader:file="audio.wav" "audio.mp3"
Then convert to m4a with faac:
faac -o audio.m4a audio.wav
Finally use the .m4a file as a fallback source in the audio tag:
<audio autoplay preload="auto" controls loop>
<source src="audio.mp3" >
<source src="audio.m4a" >
<audio>