How to play audio in iOS

Photo Jan 11, 19 08 40We can play back an audio file we’ve previously recorded or providing in the main bundle, again thanks to the AV Foundation Framework. Much like recording, it’s not as straightforward as “hitting play” somewhere. Here are the steps involved:

  • create an AVSession
  • create an AVPlayer
  • prepare for and start playing

For the method below to work we need to import and link the AVFoundation Framework to our project. We also need a property that holds the player object.

- (IBAction)playbackButtonPressed:(id)sender {
    // grab a URL to an audio asset
    NSURL *documentsURL = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
    documentsURL = [documentsURL URLByAppendingPathComponent:@"audiofile.wav"];
    // create a session
    AVAudioSession *session = [AVAudioSession sharedInstance];
    [session setCategory:AVAudioSessionCategoryPlayback error:nil];
    // create player
    self.player = [[AVAudioPlayer alloc]initWithContentsOfURL:documentsURL error:nil];
    self.player.delegate = self;
    [self.player prepareToPlay];
    [self.player play];

Stop playback at anytime by calling

[self.player stop];

Two delegate methods can inform us of the progress here:

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

- (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError *)error {
    // something didn't play so well

There are two other delegate methods that can inform us of an interruption to the playback, such as a phone call. If you’re interested in playing an MP3 file from the music library, check out the MPMediaPickerController.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.