Archive for the ‘Mobile’ Category

HTML 5 Audio playlists on iOS and Android

Posted: October 10, 2012 by Ash Mishra in Html 5, Mobile, Programming

Here is working code tested on iOS 5.x+ and Android 2.3+, using the HTML 5 Audio tag and jQuery, to play two mp3 tracks back to back.

For both Android and iOS, autoplay works (wifi on iOS 6 – not tested with 3G)

On iOS, there is even an extra: audio tracks can continue to be played with Safari in the background, and even with the screen off. Previous, Next, Play, Pause controls work too!

On Android, if the screen is off or the web page isn’t visible, the audio unfortunately won’t play the next track. Returning to the browser will start it off again though.

<!DOCTYPE html>
<html>

<head>
<meta name = "viewport" content = "width = device-width">
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>

</head>
<body>
The built-in HTML 5 audio player is shown for debug purposes. You should control the audio with the buttons below.
<audio autoplay controls="controls" id="player" x-webkit-airplay="allow" style="opacity: 1; top: 0px; left: 0px; z-index: 1; margin-bottom: 10px; display: block; width: 250px;">
 <source id="audio_source" src="audio/starbuck.mp3" type="audio/mpeg" />
</audio>
<button onClick="playNow();">Play</button>
<button onClick="pause();">Pause</button>
<button onClick="playNext();">Next</button>
<script type="text/javascript" language="javascript">
 $(function() {
 $('#player').bind('ended', playerEnded);
 $('#player').bind('canplay', playerLoaded);
 })

 function playerEnded(e) {
 // window.alert('player ended');
 if(!e) { e = window.event; }
 playNext();
 }

 function playNow() {
 $('#player').get(0).play();
 }

 function pause() {
 $('#player').get(0).pause();
 }

 function playNext() {
 if (window.HTMLAudioElement) {
 // window.alert('playing next');
 $('#audio_source').attr("src", "audio/guacamole.mp3").detach().appendTo($('#player'));
 $('#player').get(0).load();
 }
 }

 function playerLoaded() {
 // window.alert('player loaded');
 $('#player').get(0).play();
 }

</script>
</body>
</html>