10.1. Playing Audio Files

Problem

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

Solution

Use the AV Foundation (Audio and Video 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 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)viewDidLoad {
  [super viewDidLoad];
  
  self.view.backgroundColor = [UIColor whiteColor];
  
  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 != nil){
      /* Set the delegate and start playing */
      self.audioPlayer.delegate = self;
      if ([self.audioPlayer prepareToPlay] &&
          [self.audioPlayer play]){
        /* Successfully started playing */
      } else {
        /* Failed to play */
      }
    } else {
      /* Failed to instantiate AVAudioPlayer */
    }
  });
  
}

As you ...

Get iOS 6 Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.