O'Reilly logo

iOS 5 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

9.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 ...

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