Building an audio-playing application with the Audio Toolbox framework (iOS 4)

In order to demonstrate the background audio API, we need to have an application playing audio. Back in topic 12, you learned how to use the AV Foundation framework to play music inside the application. Let’s start by building a MySong application to play music with the AV Foundation framework. We’re going to use the AV Foundation framework’s audio player that you’ve already learned and add in the new Audio Toolbox framework to support background audio-playing and remote-control events.

The Audio Toolbox framework sits one level below the AV Foundation framework, so there are more methods available. The new class we’re going to use is AVAudio-Session in the Audio Toolbox framework.

First, you may want to spend some time learning new methods in AVAudioSession. AVAudioSession is a singleton object that helps you configure the audio behavior in your application. Call the following class method to get the singleton audio session: [AVAudioSession sharedInstance];

There are a few reasons for using an audio session:

■ To define the audio session category

■ To respond to the headset plug-in or unplug it

■ To handle interruptions during audio playing

Why do you need to define the audio session category? Table 22.1 show the six categories in iOS that allow you to customize the audio role in your application.


Table 22.1 Audio session category

Audio session category

Definition

AVAudioSessionCategoryAmbient

Audio playing is not the primary purpose but it allows another application’s audio to play. Will be muted when the screen is autolocked or the Silent switch is on.

AVAudioSessionCategorySoloAmbient

Default value. Only the current application will play the audio. Will be muted when the screen is autolocked or the Silent switch is on.

Table 22.1 Audio session category

Audio session category

Definition

AVAudioSessionCategoryPlayback

Audio playing is the primary purpose in this application. Won’t allow other applications to play along. Won’t be muted even if the Silent switch is on. Supports background audio playing.

AVAudioSessionCategoryRecord

Audio recording is the primary purpose. Continues recording when the screen is autolocked.

AVAudioSessionCategoryPlayAndRecord

For audio playing and recording at the same time or not, i.e., voice over IP This setting will mute the other application’s audio.

AVAudioSessionCategoryAudioProcessing

Not playing audio or recording but processing the audio, such as format conversion.

When you set the category to playback, the system knows your application’s main purpose is to play music, and it should continue playing even when the application isn’t active. By default, this value in the audio session’s category is AVAudioSession-CategorySoloAmbient, and the system will stop the audio playing when the application is inactive. Because we’re building an audio-playing application that supports continuous audio playing in the background, we need to set the audio session category to playback.

Use this code snippet to define the audio session’s category to playback:

tmp80-71_thumb

Let’s build the audio-playing application with both the Audio Toolbox and AV Foundation frameworks in Xcode. Create a new project, use the View-Based Application template in the iOS application, and name it MySong. Because we’re going to use the AV Foundation and Audio Toolbox frameworks in this application, go ahead and add in the needed extra frameworks. Include the header files inside the MySongView-Controller.h file:

tmp80-72_thumb

Let’s add an audio file called backgroundmusic.m4a into our project. That’s the audio file we’ll play in the application. You can use any music or audio file available on your own computer; just make sure the name matches the example in this project.

What is M4A format?

Files in M4A format are actually the audio layer of (nonvideo) MPEG 4 movies. M4A is slated to become the new standard for audio file compression.

Next, we’ll design the UI inside the MySong view controller. There will be a text label to display the current audio file’s name in the center of the screen, and below the label will be three buttons: one button for play/pause events, one for fast-forward, and another one for rewind. When you tap the Play button, the button image will flip to Pause, indicating you can pause the currently playing audio.

In order to have a better user experience, let’s add the background images for the three buttons into our project.

Select the MySongViewController.h file, and add in the new changes, as shown in the following listing.

Listing 22.3 Project MySong’s view controller header file

Listing 22.3 Project MySong's view controller header file

In the header file, you add in one label for the filename and three buttons for the audio playing control. Three methods are defined to handle each button’s touch event.

Save the changes for the header file. Next, let’s add the new objects to the nib file and connect them to the view controller’s header file.

Click the MySongViewController.xib file to open it for editing, and then open the object library. First, add a new text label into the view, and then drag three buttons into the view. By default, the button’s type is a rounded rectangle. Let’s change the button’s attributes to a custom type and assign the background image to each button. Once it’s complete, you’ll see the view controller’s UI, similar to the one shown in figure 22.2.

Single-click the file’s owner under the MySongViewController’s File panel. Go to the connection inspector and make sure all four UI outlets in the file’s owner are connected to new subviews. Hook up the three action buttons and save everything.

Now we’ll move on to implement the MySongViewController.m file. There are many changes in the next step, considering this is a comprehensive audio playing project.

 MySong's view controller UI

Figure 22.2 MySong’s view controller UI

Select the file and add in the code according to the following listing.

Listing 22.4 MySongViewController.m file

Listing 22.4 MySongViewController.m file

 

 

 

Listing 22.4 MySongViewController.m file

 

 

 

Listing 22.4 MySongViewController.m file

Let’s review what you’ve changed inside this view controller file.

You want to use the Play/Pause button to toggle between play and pause, so you define the method updateViewForPlayerState O to update the Play/Pause button’s background image, indicating the audio player’s status. The method pausePlayback-ForPlayer © can pause the audio player and update the UI. The method startPlay-backForPlayer © will start playing the audio file if the audio player is not playing.

The method rewind © can control the audio player’s timeline to go back 3 seconds, and the method fastforward © will control it to fast-forward 3 seconds.

The action method playButtonPressed © will respond to the Play/Pause button’s action event. The action methods rewButtonPressed © and ffwButtonPressed © will respond to the Rewind button’s action and the Fast-forward button’s action, respectively.

Then you define the audio player’s delegate callbacks in audioPlayerDidFinish-Playing ©, audioPlayerBeginInterruption 1), and audioPlayerEndInterruption 1!. In audioPlayerDidFinishPlaying ©, when the audio playing task is complete, you reset the timeline back to the beginning. When an interuption occurs in the system, the delegate callbacks give you the chance to update the UI. When the interup-tion is gone, you need to resume playing the music.

Finally, in viewDidLoad 1@, you first define the audio player’s music file as back-groundmusic.m4a and then customize the view controller’s UI by displaying the file’s name in the label fileName. In addition, you want to autoplayback this music file 10 times and set the delegate to self.

Then inside the audio session 1#, you define the category as AVAudioSession-CategoryPlayback to inform the system that this application will use audio playing as a primary function.

Finally, you release the retained objects inside the dealloc 1$.

That’s all! Change the target to a universal application for both iPhone and iPad. Save all the changes, click Build, and run it in Xcode.

If everything runs smoothly, you should see a comprehensive audio-playing application launch on your iPhone or iPad that contains a Play/Pause button, Fast-forward button, and Rewind button. The text label will display the audio file’s name, as shown in figure 22.3.

Play with this application a bit, and you will find that our application has the first priority in audio playing. For example, try to play music using the iPod system app in the background, and when this application starts playing audio, the system will mute the iPod music; this application will continue playing even if the screen is autolocked.

When you have an incoming phone call, this application will pause playing the current music as defined in the interruption-handling methods.

The audio-playing application when it's launched on the iPhone and iPad

Figure 22.3 The audio-playing application when it’s launched on the iPhone and iPad

This application uses fast app switching to automatically handle the different application’s life transitions. You just built an advanced audio-playing application with the Audio Toolbox and AV Foundation frameworks. Keep in mind that the audio session category is important for audio-playing applications.

Now let’s continue with our multitasking project to enable background audio playing and handle remote-control events.

Next post:

Previous post: