Playing audio from the iPod library (iOS 4)

In the previous topic, we discussed the basics of images. This topic will detail how to play and record various types of audio and video. This will include how to play back audio items in the user’s iPod library as well as how to record to and play from the user’s video library.

To further demonstrate these concepts, you’ll create two sample applications. The first application is a simple media player that lets the user choose a song from their iPod library and play it back within the application. The next will be a simple recording and playback application that lets the user record audio of an arbitrary length and play it back.

You may wonder: why do you want to play music from the iPod music library. Many people bought their fancy new iPhones for the sole purpose of combining their electronics (cell phone, iPod, GPS, camera, and so on).

Apple saw the need for such control within an application and provided the Media Player framework to allow you to retrieve items from the iPod media library as well as play them.

There are many reasons why you’d want to have control over the iPod in your applications. You may want to allow the user to use their personal music instead of your game music, or you may want to create a "Name That Tune" sort of game that uses songs from the user’s iPod library. Apple has now made it simple to access and play these items. We’ll look at how to retrieve items from the media library, how to get information about an item, and how to play an item, and we’ll put it all together in a concrete example at the end of the section.

Retrieving audio items from the iPod media library

Retrieving items from the iPod media library is similar to retrieving photos from the photo library. The process is as follows:

1 Display the MPMediaPickerController in the current view.

2 Select media items from the iPod library.

3 A callback method in the MPMediaPickerControllerDelegate is called with the media items.

The following example demonstrates how to display the MPMediaPickerController to select media items:


MPMediaPickerController allows you to select multiple items. To enable this feature, you must set the allowsPickingMultipleItems property to YES.

Because MPMediaPickerController is a view controller, it can be displayed any way that you can display a view controller. It can be inside a tab bar view controller, pushed onto a navigation controller stack, or, in this case, presented as the modal view controller. How you choose to display it is up to you. Make sure you choose the method that fits the flow of your application. Figure 12.1 shows what the MPMediaPickerController looks like when displayed.

The media types you select aren’t limited to music. You can also select podcasts and audio books. When you initialize a new MPMediaPickerController, you have the option of selecting what type of media is shown by default. In the previous example, the picker will display the user’s music library. Following in table 12.1 are the constants you can use to change which library is shown.

The MPMediaPickerController

Figure 12.1 The MPMediaPickerController

After you’ve created your MPMediaPickerController, you need to create a delegate to respond to two methods: mediaPicker:didPickMediaItems: and mediaPicker-DidCancel:.mediaPickerDidCancel: is called when the user presses the Cancel button in the toolbar. Typically, you want to hide the MPMediaPickerController from this method.

Table 12.1 Media constants




The media type is music, and the picker is limited to the music library.


The media type is a podcast, and the picker is limited to the podcast library.


The media type is an audio book, and the picker is limited to the audio book library.


The media type is an unspecified type of audio. The picker isn’t limited to any specific audio type.


Similar to MPMediaTypeAnyAudio. This allows the picker to pick any audio item from the library.

When a media item has been selected, the mediaPicker:didPickMediaItems: method of the delegate automatically is called with an MPMediaItemCollection containing the selected item. An MPMediaItemCollection is a sorted set of MPMediaItems.

Getting information about an MPMediaItem

When you select an MPMediaItem from the iPod’s media library, it comes with all the associated meta-information. To get access to this information, you call the valueFor-Property: method of the MPMediaItem with a given key. The complete list of keys can be found in the API documentation for MPMediaItem. Table 12.2 provides a short list of some of the more common keys.

Table 12.2 Common MPMediaItem keys




Corresponds to one of the media types discussed in table 12.1


The title of the album that the media item belongs to


The artist of the current media item


An NSInteger that represents the length in seconds of the current media item


The artwork image for the media item

Other properties you have access to include genre, composer, duration, track and disc number, album artwork, rating, lyrics, last played date, and play and skip counts.

Now that you know how to select media items from the iPod library, playing these items is fairly easy.

Playing media items using MPMusicPlayerController

The class used to play media items is MPMusicPlayerController. It gives you total control over the built-in iPod on the device.

When initializing a new MPMusicPlayerController, you have two options for interacting with the iPod. The first way limits the iPod playback to your application. When you choose this method of playback, the iPod will stop playing as soon as your application exits. The other allows you to invoke the global iPod application. Exiting your application won’t cause the iPod to stop playing. The following code snippet details how to initialize the MPMusicPlayerController:


By using the applicationMusicPlayer method of MPMusicPlayerController, you’re limiting the media playback to your application. Using this method doesn’t affect the device’s iPod state in any way. If you want to use the main iPod application for media playback, you use the iPodMusicPlayer method.

After you’ve initialized the MPMusicPlayerController, you need to tell it which items you want it to play. You do so with the setQueueWithItemCollection: method. This method takes an MPMediaItemCollection as an argument. Conveniently enough, an MPMediaItemCollection is available to you when the MPMediaPickerController selects an item. Here’s an example detailing how to set up the media player to play items selected from the user’s media library:


After you set up the MPMusicPlayerController, quite a few settings are available to further control the iPod (see table 12.3).

Table 12.3 Common iPod control properties




The current playback time in seconds.


A reference to the currently playing item in the queue.


The current playback state of the media player. The states are stopped, playing, paused, interrupted, seeking forward, and seeking backward.


The repeat mode of the player. The repeat modes are default, none, one, and all.


The shuffle mode of the player. The shuffle modes are default, off, songs, and albums.


The volume of the player. This is a float value between 0.0 and 1.0.

See the documentation for the names of the constants for playbackState, repeat-Mode, and shuffleMode.

The MPMusicPlayerController provides a full set of methods that you’d expect to control the playback of the iPod. Table 12.4 provides a complete list of these methods as well as their descriptions.

Table 12.4 Playback control methods for MPMusicPlayerController




Starts or resumes the iPod’s playback of the current media item.


Pauses the playback if the player is currently playing.


Stops the playback if the player is currently playing.


Moves playback forward at a faster than normal rate.

Table 12.4 Playback control methods for MPMusicPlayerController




Moves playback backward at a faster than normal rate.


Stops seeking and resumes playback.


Starts playback of the next media item in the playback queue. This method ends playback if it’s already at the last item in the queue.


Starts playback of the current media item at the beginning.


Starts playback of the previous media item in the playback queue. This method ends playback if it’s already at the first item in the queue.

As you can see, the API gives you quite a bit of control over the iPod. With all of these controls, you’re able to create fully featured media playback applications. In the next section, we’ll show you how to put it all together, and you’ll create a simple media player application.

Example: creating a simple media player application

You’ve already written most of the code needed to create a simple media player application. This example will demonstrate how to use the MPMediaPickerController to find media and then play it using the MPMusicPlayerController.

Make sure you’re testing directly on your device, because the Simulator doesn’t have an iPod application. Testing from the Simulator will yield an error when trying to display the picker.


You’ll start the application from the View-Based Application template provided by Apple. This template creates an application delegate as well as a view controller. The View-Based Application is perfect, because you’ll only need to add three buttons to the view. Name the application iPodTest.


This project requires one more framework beyond the defaults provided by the View-Based Application template: MediaPlayer.framework. To add it, right-click Frameworks and select Add; then, select Existing Frameworks. Search for Media-Player.framework and select it.


Before you create the interface, you need to create the actions that the buttons will connect to. Open iPodSampleViewController.h, and add the code in the next listing.

Listing 12.1 iPodSampleViewController.h

Listing 12.1 iPodSampleViewController.h


Listing 12.1 iPodSampleViewController.h

The first import is added by default. The next two are needed to access the music player and media picker. They contain all the classes and methods that you’ll be referencing.

Looking at the class signature for iPodTestViewController, you see that it implements the MPMediaPickerControllerDelegate interface. This means the class is the delegate for the MPMediaPickerController. It receives all the actions sent by the media picker and allows you to respond to them.

After declaring the media player and media picker, you declare the IBActions. These actions are hooked up to the UIButtons on the interface. As you can see, you implement only two of the nine methods found in MPMusicPlayerController. Because the rest of the methods are similar, we’ll leave implementing them up to you.


Open iPodTestViewController.xib for editing. Drag three UIButtons from the library onto your view, and title them Pick Media, Play, and Stop. Connect each of them to its corresponding IBAction by right-clicking it and dragging to the File’s Owner icon. The interface should look like figure 12.2.

Next you will need to edit the view controller implementation file and add the code that will control this interface


Open iPodTestViewController.m, and add the code in the following listing.

 A simple media player interface

Figure 12.2 A simple media player interface

Listing 12.2 iPodTestViewController.m

Listing 12.2 iPodTestViewController.m



Listing 12.2 iPodTestViewController.m

You begin by initializing the media player and picker. Because the player is being initialized with the iPodMusicPlayer method, the application uses the global iPod player when playing media items. The media picker is initialized with the MPMediaType-AnyAudio constant; this lets the user select any sort of audio media from the iPod library. Finally, you set the class as the delegate to the MPMediaPickerController so you can respond to its actions.

The mediaPicker method is called automatically whenever the user selects an audio item from the iPod library. It receives an MPMediaItemCollection, which contains the audio item to be played. The next line takes this collection and adds it to the iPod media collection’s queue. To hide the picker, you call dismissModalView-ControllerAnimated.

The pickMedia method displays the media picker on top of the current view. The playMedia and stopMedia methods are fairly self-explanatory because they only control the media player. Use these methods as a template for implementing other media player controls on your own.

Finally, you need to make sure to release objects that you allocate. Doing so ensures that your application doesn’t use more memory than it needs and runs as efficiently as possible.

In the next section, we’ll discuss how to let users record audio files.

Next post:

Previous post: