Play an MP3 Audio Stream in PhoneGap

I work for a company that owns a couple radio stations as well as a popular classifieds website (http://www.ksl.com). We wanted to build an iPhone app that would allow the customer to browse the classifieds website while listening to the audio stream. I decided to implement that using the PhoneGap framework. I'm embarrassed to admit that it took me about 2 days to test all the various suggestions I found on the web and to find this answer. But, alas, here is the working bit of JavaScript code that will start a stream in the background.

function playStream() {
  try {
    var myaudio = new Audio('http://icecast.ksl.com:8000/');
    myaudio.id = 'playerMyAdio';
    myaudio.play();
  } catch (e) {
    alert('no audio support!');
  } 
}

Then, in the HTML page I have the following.

<button onclick="playStream()">Listen Live</button>

If myaudio was created in a global sense (outside of a function) than you can also pause the audio with the following.

myaudio.pause();

Background Audio

In iOS 4.0 and above you can run audio in the background. PhoneGap doesn't currently support this out of the box, but you can add it. To do so, you'll need to do two things; add an item to the info.plist file and add a line of code to PhoneGap.

To the info.plist file, add a new key of “Required background modes”. That key will have an array of options. In “Item 0” of that array set the value to “App plays audio”.

Next, modify the ~/PhoneGapLib/Classes/Sound.m file. Look for the line that contains “if ([resourceURL isFileURL]) {”. It's around line 103. Just below that line, inside the if statement, you'll want to add the following.

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];

So, that section of code will look like the following.

if ([resourceURL isFileURL]) {
	[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
	audioFile.player = [[ AVAudioPlayer alloc ] initWithContentsOfURL:resourceURL error:&error];
} else {
	NSData* data = [NSData dataWithContentsOfURL:resourceURL];
	audioFile.player = [[ AVAudioPlayer alloc ] initWithData:data error:&error];
}

Note: Some users have have had trouble finding the Sound.m file. It's not in the XCode project itself. You'll find it beneath your home directory (~) under ~/PhoneGapLib/Classes/ or you can just use Finder to search for Sound.m. Right-click on it and open it in XCode.

Working HTML Example

Below is an HTML page that has the code above on it and should work in your typical web browser.

stream.html

Contributors

Many thanks to the people who write to me and ask questions about this. I don't work with PhoneGap that often but the questions help me refine these instructions and make them more clear. That helps even more developers. You know who you are.


comments powered by Disqus
play_an_mp3_audio_stream_in_phonegap.txt · Last modified: 2013/07/26 21:29 by Joel Dare