We 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
- (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
1 |
[self.player stop]; |
Two delegate methods can inform us of the progress here:
1 2 3 4 5 6 7 8 9 |
- (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.
- https://developer.apple.com/library/ios/DOCUMENTATION/AVFoundation/Reference/AVAudioPlayerClassReference/Reference/Reference.html
- https://developer.apple.com/library/ios/documentation/mediaplayer/reference/MPMediaPickerController_ClassReference/Reference/Reference.html
- http://pinkstone.co.uk/how-to-record-audio-from-the-microphone-in-ios/