Tag Archive for 'AVAudioPlayer'

Playing Audio Files using the iPhone SDK

Playing sound is a big part of any rich media application and it's very likely you'll need to do it in your future iPhone apps. Before version 2.2 of the SDK this was somewhat difficult -- you needed to either roll your own player or use AudioQueueServices. To use the latter you have to create a bunch of C-style structures and callbacks to feed the data manually byte by byte. It's a very programming intensive process while all you want to do is just load and play a sound!

To remedy this problem Apple introduced a new Framework: AVFoundation and a new audio player: AVAudioPlayer. It has the simplicity you desire but the features you need in order to play your audio files: play, stop, seek, and pause. You can also choose to register a delegate to get certain events like errors in playback, notification when playback ends, and interruption events for when phone calls occur. Pretty cool stuff.

I've written up an example application which is checked into SVN at http://code.9mmedia.com/svn/public/iphone/audio-example/ but here are the key points:

//Make sure you're building for 2.2 and you are also including AVFoundation.framework
 
#import <AVFoundation/AVFoundation.h>
AVAudioPlayer* player;
...
/* Both these actions are hooked up to buttons in IB */
- (IBAction)startPlayback:(UIButton *)sender {
    if(!player){
        /*
         * Here we grab our path to our resource
         */
        NSString* resourcePath = [[NSBundle mainBundle] resourcePath];
        resourcePath = [resourcePath stringByAppendingString:@"/grabbag.m4a"];
        NSLog(@"Path to play: %@", resourcePath);
        NSError* err;
 
        //Initialize our player pointing to the path to our resource
        player = [[AVAudioPlayer alloc] initWithContentsOfURL:
                            [NSURL fileURLWithPath:resourcePath] error:&err];
 
        if( err ){
            //bail!
            NSLog(@"Failed with reason: %@", [err localizedDescription]);
        }
        else{
            //set our delegate and begin playback
            player.delegate = self;
            [player play];
        }
    }
}
- (IBAction)pausePlayback:(UIButton*)sender {
    NSLog(@"Player paused at time: %f", player.currentTime);
    [player pause];
}

That's all you need to do to play a sound... create a file URL, init, and play! Pausing is done by a simple method call, and you can monitor the location in the song by checking the currentTime property of the object.

Make sure to check out the project to see the delegate methods implemented, and the implementation of the code above! Also make sure to check the iPhone documentation for these classes as well:
  • AVAudioPlayer Documentation (apple.com)
  • AVAudioPlayerDelegate Documentation (apple.com)

23 Comments