An easy way to play streaming audio using MPMoviePlayerController

Every once in a while, you find the need to play some steaming audio file in your app. Of course, you can use the new AVPlayer class that is available in iOS 4 and later to do so. Or you can check out this AudioStreamer written by Matt Gallagher. They both will get the work done and provide you with plenty of extra good stuff such as streaming multiple audio files. However, if the only need is to simply play a single audio file online, you have a better choice, that is to use the MPMoviePlayerController (available in iOS 2 and later). Guess what, it also comes with a nice basic graphical audio controls (play/pause, duration, progress bar) so that you don’t have to write yourself!

All you have to do is to add the MediaPlayer framework in your project and import the related header files. And then you set it up as follows:

MPMoviePlayerController* moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL: audioURL];
[moviePlayer.view  setFrame:CGRectMake()]; // some rect area where you want the audio controls to live
[viewController.view addSubview:moviePlayer.view];
[moviePlayer prepareToPlay];

* Please note that, in iOS 4 when you call initWithContentURL: method, the prepareToPlay method will be called automatically but only for the first time. However, in iOS 5 you will need to call prepareToPlay manually to make it work, otherwise, the audio controls will not show up properly.

Also, if you need to change the contentURL for the moviePlayer to play another file, do:

moviePlayer.contentURL = newURL;
[moviePlayer prepareToPlay]; // make sure to call this every time you change the url!

One last note, the property shouldAutoplay is set to be NO by default in iOS 4. You will have to manually set it to NO in iOS 5 if you don’t what the player to start play automatically.

About these ads

One thought on “An easy way to play streaming audio using MPMoviePlayerController

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s