O'Reilly logo

iOS 7 Programming Cookbook by Vandad Nahavandipoor

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

12.1. Playing Audio Files

Problem

You want to be able to play an audio file in your application.

Solution

Use the AV Foundation framework’s AVAudioPlayer class.

Discussion

The AVAudioPlayer class in the AV Foundation framework can play back all audio formats supported by iOS. The delegate property of an instance of AVAudioPlayer allows you to get notified by events, such as when the audio playback is interrupted or when an error occurs as a result of playing an audio file. Let’s have a look at a simple example that demonstrates how we can play an audio file from the application’s bundle:

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player
                       successfully:(BOOL)flag{

    NSLog(@"Finished playing the song");

    /* The [flag] parameter tells us if the playback was successfully
     finished or not */

    if ([player isEqual:self.audioPlayer]){
        self.audioPlayer = nil;
    } else {
        /* Which audio player is this? We certainly didn't allocate
         this instance! */
    }

}

- (void)viewDidLoad {
    [super viewDidLoad];

    dispatch_queue_t dispatchQueue =
    dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

    dispatch_async(dispatchQueue, ^(void) {
        NSBundle *mainBundle = [NSBundle mainBundle];

        NSString *filePath = [mainBundle pathForResource:@"MySong"
                                                  ofType:@"mp3"];

        NSData   *fileData = [NSData dataWithContentsOfFile:filePath];

        NSError  *error = nil;

        /* Start the audio player */
        self.audioPlayer = [[AVAudioPlayer alloc] initWithData:fileData
                                                         error:&error];

        /* Did we get an instance of AVAudioPlayer? */
        if (self.audioPlayer ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required