iOS Programming 101: Record and Play Audio using AVFoundation Framework
Editor’s note: Some of you asked us to write a tutorial about audio recording. This week, we work with Yiqi Shi and Raymond from Purple Development to give you an introduction of AVFoundation framework. Yiqi and Raymond are independent iOS developers and have recently released Voice Memo Wifi that allows users to record voice memo and share it over WiFi.
iOS provides various framework to let you work with sound in your app. One of the frameworks that you can use to play and record audio file is the AV Foundation Framework. In this tutorial, I’ll walk you through the basics of the framework and show you how to manage audio playback, as well as, recording.
To provide you with a working example, I’ll build a simple audio app that allows users to record and play audio. Our primary focus is to demonstrate the AV Foundation framework so the user interface of the app is very simple.
The AV Foundation provides easy ways to deal with audio. In this tutorial, we mainly deal with these two classes:
- AVAudioPlayer – think of it as an audio player for playing sound files. By using the player, you can play sounds of any duration and in any audio format available in iOS.
- AVAudioRecorder – an audio recorder for recording audio
Starting with the Project Template
First of all, create a “Single View Application” and name it as “AudioDemo”. To free you from setting up the user interface and code skeleton, you can download the project template from here.
I’ve created a simple UI for you that it only contains three buttons including “Record”, “Stop” and “Play”. The buttons are also linked up with the code.

AudioDemo Project Template
Adding AVFoundation Framework
By default, the AVFoundation framework is not bundled in any Xcode project. So you have to add it manually. In the Project Navigator, select the “AudioDemo” project. In the Content Area, select “AudioDemo” under Targets and click “Build Phases”. Expand “Link Binary with Libraries” and click the “+” button to add the “AVFoundation.framework”.

Adding AVFoundation Framework
To use the AVAudioPlayer and AVAudioRecorder class, we need to import
1 |
#import <AVFoundation/AVFoundation.h> |
Audio Recording using AVAudioRecorder
First, let’s take a look how we can use AVAudioRecorder to record audio. Add the AVAudioRecorderDelegate protocol and AVAudioPlayerDelegate in the ViewController.h. We’ll explain both delegates as we walk through the code.
1 |
@interface ViewController : UIViewController <AVAudioRecorderDelegate, AVAudioPlayerDelegate> |
Next, declare the instance variables for AVAudioRecorder and AVAudioPlayer in ViewController.m:
1 2 3 4 |
@interface ViewController () { AVAudioRecorder *recorder; AVAudioPlayer *player; } |
The AVAudioRecorder class provides an easy way to record sound in iOS. To use the recorder, you have to prepare a few things:
- Specify a sound file URL.
- Set up the audio session.
- Configure the audio recorder’s initial state.
We’ll do the setup in the “viewDidLoad” method of ViewController.m. Simply edit the method with the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
- (void)viewDidLoad { [super viewDidLoad]; // Disable Stop/Play button when application launches [stopButton setEnabled:NO]; [playButton setEnabled:NO]; // Set the audio file NSArray *pathComponents = [NSArray arrayWithObjects: [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject], @"MyAudioMemo.m4a", nil]; NSURL *outputFileURL = [NSURL fileURLWithPathComponents:pathComponents]; // Setup audio session AVAudioSession *session = [AVAudioSession sharedInstance]; [session setCategory:AVAudioSessionCategoryPlayAndRecord error:nil]; // Define the recorder setting NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc] init]; [recordSetting setValue:[NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey]; [recordSetting setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey]; [recordSetting setValue:[NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey]; // Initiate and prepare the recorder recorder = [[AVAudioRecorder alloc] initWithURL:outputFileURL settings:recordSetting error:NULL]; recorder.delegate = self; recorder.meteringEnabled = YES; [recorder prepareToRecord]; } |
Note: For demo purpose, we skip the error handling. In real app, don’t forget to include proper error handling.
In the above code, we first define the sound file URL for saving the recording. and then configure the audio session. iOS handles audio behaviour of an app by using audio sessions. Upon launch, your app automatically gets an audio session. You can grab such session by calling [AVAudioSession sharedInstance] and configure it. Here, we tell iOS that the app uses “AVAudioSessionCategoryPlayAndRecord” category which enables both audio input and output. We will not go into the details of audio session but you can check out the official document for further details.
The AVAudioRecorder uses a dictionary-based settings for its configuration. In line 21-25, we use the options keys to configure the audio data format, sample rate and number of channels. Lastly, we initiate the audio recorder by calling “prepareToRecord:” method.
Note: For other settings keys, you can refer to AV Foundation Audio Settings Constants.
Implementing Record Button
We’ve completed the audio preparation. Let’s move on to implement the action method of Record button. Before we dive into the code, let me explain how the “Record” button works. When user taps the “Record” button, the app will start recording and the button text will be changed to “Pause”. If user taps the “Pause” button, the app will pause the audio recording till the “Record” is tapped again. The audio recording will only be stopped when user taps the “Stop” button.
Edit the “recordPauseTapped:” method with the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
- (IBAction)recordPauseTapped:(id)sender { // Stop the audio player before recording if (player.playing) { [player stop]; } if (!recorder.recording) { AVAudioSession *session = [AVAudioSession sharedInstance]; [session setActive:YES error:nil]; // Start recording [recorder record]; [recordPauseButton setTitle:@"Pause" forState:UIControlStateNormal]; } else { // Pause recording [recorder pause]; [recordPauseButton setTitle:@"Record" forState:UIControlStateNormal]; } [stopButton setEnabled:YES]; [playButton setEnabled:NO]; } |
In the above code, we first check whether the audio player is playing. If audio player is playing, we simply stop it by using the “stop:” method. Line 7 of the above code determines if the app is in recording mode. If it’s not in recording mode, the app activates the audio sessions and starts the recording. For recording to work (or sound to play), your audio session must be active.
In general, you can use the following methods of AVAudioRecorder class to control the recording:
- record – start/resume a recording
- pause – pause a recording
- stop – stop a recording
Implementing Stop Button
For the Stop button, we simply call up the “stop:” method to the recorder, followed by deactivating the audio session. Edit the “stopTapped:” method with the following code:
1 2 3 4 5 6 |
- (IBAction)stopTapped:(id)sender { [recorder stop]; AVAudioSession *audioSession = [AVAudioSession sharedInstance]; [audioSession setActive:NO error:nil]; } |
Implementing the AVAudioRecorderDelegate Protocol
You can make use of AVAudioRecorderDelegate protocol to handle audio interruptions (say, a phone call during audio recording) and the completion of recording. In the example, the ViewController is the delegate. The methods defined in AVAudioRecorderDelegate protocol are optional. Here, we’ll only implement the “audioRecorderDidFinishRecording:” method to handle the completion of recording. Add the following code to ViewController.m:
1 2 3 4 5 6 |
- (void) audioRecorderDidFinishRecording:(AVAudioRecorder *)avrecorder successfully:(BOOL)flag{ [recordPauseButton setTitle:@"Record" forState:UIControlStateNormal]; [stopButton setEnabled:NO]; [playButton setEnabled:YES]; } |
After finishing the recording, we simply change the “Pause” button back to “Record” button.
Playing Sound using AVAudioPlayer
Finally, it comes to the implementation of the “Play” button for audio playback using AVAudioPlayer. In the ViewController.m, edit the “playTapped:” method using the following code:
1 2 3 4 5 6 7 |
- (IBAction)playTapped:(id)sender { if (!recorder.recording){ player = [[AVAudioPlayer alloc] initWithContentsOfURL:recorder.url error:nil]; [player setDelegate:self]; [player play]; } } |
The above code is very straightforward. Normally, there are a few things to configure an audio player:
- Initialize the audio play and Assign a sound file to it. In the case, it’s the audio file of the recording (i.e. recorder.url).
- Designate an audio player delegate object, which handles interruptions as well as the playback-completed event.
- Call play: method to play the sound file.
Implementing the AVAudioPlayerDelegate Protocol
The delegate of an AVAudioPlayer object must adopt the AVAudioPlayerDelegate protocol. In this case, it’s the ViewController. The delegate allows you to handle interruptions, audio decoding errors and update the user interface when an audio has finished playing. All methods in AVAudioplayerDelegate protocol are optional, however. To demonstrate how it works, we’ll implement the “audioPlayerDidFinishPlaying:” method to display an alert prompt after the completion of audio playback. For usage of other methods, you can refer to the official documentation of AUAudioPlayerDelegate protocol.
Add the following code in ViewController.m:
1 2 3 4 5 6 7 8 |
- (void) audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{ UIAlertView *alert = [[UIAlertView alloc] initWithTitle: @"Done" message: @"Finish playing the recording!" delegate: nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alert show]; } |
Compile and Run Your App
You can test audio recording and playback using a physical device or software simulator. If you test the app using actual device (e.g. iPhone), the audio being recorded comes from the device connected by the built-in microphone or headset microphone. On the other hand, if you test the app by using the Simulator, the audio comes from the system’s default audio input device as set in the System Preference.
So go ahead to compile and run the app! Tap “Record” button to start recording. Say something, tap the “Stop” button and then select the “Play” button to listen the playback.

AudioDemo App
For your reference, you can download the complete source code from here. Feel free to leave me comment if you have any questions.
This post is contributed by Yiqi Shi and Raymond from Purple Development. Yiqi and Raymond are independent iOS developers and have recently released Voice Memo Wifi that allows users to record voice memo and share it over WiFi.
Comments
Reem
AuthorAmazing tutorial
thank you so mach
Damien
AuthorGreat tutorial – very helpful!
망각인간
AuthorAwesome!
Thanks for simon ng, Thanks for Raymond.
Thanks to the always helpful.
kevin chen
AuthorWonderfully, thanks!
pantgurra
AuthorI would like a tutorial how external sound, music, singing, talking etc can trigger an action, animation, image etc. Thanks for the great turorials btw, youre doing a great job!
Alex
AuthorThat’s great! Would be possible to extend this with a voice recognition engine? E.g. I record 3 messages: 1) hello, 2) bread 3) night and then when I press a “recognize button” the app understands if what am I repeating is “hello” or “bread” or “night”? Mission impossible? 🙂
Simon Ng
AuthorI am still waiting for Apple to open up Siri API for speech recognition. However, if you’re looking for speech recognition engine, you can take a look at OpenEars: http://www.politepix.com/openears/
VladislavKovalyov
AuthorHow can I save my recorded audio?
Rikin Katyal
AuthorI was wondering the same thing
sol
AuthorYeah ME TOO!!!!!
Shanmugasundharam Selvadurai
Author“NSSearchPathForDirectoriesInDomains” it stored in simulator
onmywy133
AuthorWhy does playing sound not require Audio Session ?
Kamran
Authorhow to record more than one msges e.g 1.hello 2. hi 3, country… and how to store these msges in table list and then play selected msges from tablelist …please tell me…thnks in advance
Mitchell
AuthorI am using XCode 4.2, IOS 5, MacOS 10.6.8.
Do you have source code for the above combination please?
tung
Authorgo to “Show the File inspector” check autolayout isn’t ticked.
Innovative
AuthorHow the user will be able to attach the additional recording to the beginning, overlay in the middle or append to the end of the original audio recording.?
Aneta Karbowiak
AuthorHi,
I
ve read your tutoria and it
s very usefull but I wanted to ask you something more. Ive a project with several collision detections and after each collision appears a number. I added a sound for every number. My problem is that the numbers appears correctly after each collision: 1,2,3,4.... but the sound doesn
t follow the numbers. It does like this: four, four, one, three, three…Do you know why and how to fix it?
Aneta
AuthorNever mind. I`ve already did it.
Thakur
AuthorBy looking at this tutorial Now I would Like to learn something different. Can you make an Audio apps Tutorial which shows Audio Name in Table View and play song with Play Pause Button. Can you Please make a tutorial something like that 🙂
sol
AuthorYEAH PLEASE!
Slogan
AuthorIs there a way to modify this code so that instead of recording audio using the microphone (hardware), the record button records sounds that the phone is making/outputting? I have programmed a few buttons to make noises, and I want to be able to record a sequence of those noises and play back that recording.
Innovative
AuthorI am running this code in iOS 7, it is not working. May i know how to record and set framerate to some xxfps(eg:24fps).? Thanks in advance.
Евгений Михайлов
AuthorNote: For demo purpose, we skip the error handling. In real app, don’t forget to include proper error handling.
What do you mean by it?
velociround
AuthorAll parameters which receive an NSError pointer, such as [session setCategory:AVAudioSessionCategoryPlayAndRecord error:nil] have not been properly handling. If an error were to ever occur, you’d have no idea what happened and your application will not work properly (might even crash depending on what you’re trying to do).
This is still not proper error handling and I don’t recommend using that either, but it will tell you on the console what happened:
NSError *error;
[session setCategory:AVAudioSessionCategoryPlayAndRecord error:&error];
if (error) {
NSLog(@”Erro! %@”, error.debugDescription);
}
Claire
AuthorAwesome tutorial! Thank you 🙂
tung ta
Authorthanks, nice tutorial!
nagendra
Authorthanks, nice tutorial.,.
Ваше Онтатиле Масвибилили
AuthorHow would i use metering(measuring the level of audio input)?
Jimm
AuthorGreat intro into AVAudio! Thanks
హరి కృష్ణ
AuthorI have a TableView Contains List of Urls and When i did selectRow In the next view AVPlayer should Play,Pause etc….
my task is that song should be played When it is in Background or When it goes to AnotherView i.e. TableView. I have Some code Like This and i pasted in AppDelegate
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
[[AVAudioSession sharedInstance] setDelegate:self];
now its played in background. But it doesn’t play when we back to TableViewController from PlayerView
Please help me my E-mail is [email protected]
harikrishna
Authorhi
Hasan
AuthorVery useful tutorial. Can you please please please do one using Swift language?
Thanks a lot.
John D. Storey
AuthorThanks 🙂 This was a great tutorial! Keep ’em coming guys
Hasan
AuthorHi, can you please the same tutorial using swift? I couldn’t find any helpful guideline. Thanks
harikrishna
AuthorShell we record the playing song in the Background
HelpPlease
AuthorWhat would i need to do if i wanted to have two buttons to record separate recordings?
I’m a beginner…
sdfsdf
Authoru have put that code link, but its empty buttons there oin xcode project….
check out dear…
Fortuna
AuthorHow can I test the latency of the record audio?
alijnclarke
AuthorGot this working perfectly, but i just wondered how i can set it up so that incoming text message notifications are not muted when recording?
Currently the notification pops up but there is no sound 🙁
(I know this is most likely a dead thread)
Lukasz Rutkowski
AuthorTo make the audio louder add this line to the Session setup part:
[session overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:nil];
Vimal Raval
Authorcan we test in simulator ?
Michael Mork
AuthorI am getting a very uninformative and frustrating error:
“fatal error: unexpectedly found nil while unwrapping an Optional value”
when attempting to instantiate the AVAudioRecorder; I am not passing optional values.
Davut Temel
Authori make a karaoke app. it is recording success (background mp3 and my voice mix) when headphone was not plugin. but headphone plugin and listen record, i cant hear background music (its too low). how can i do that? please help me.
Ram Gade
AuthorHow do i record audio using auxillary. cable on ipad.
Manish Patel
AuthorHi,
I am using your code with iOS9. Now it is working fine if I record and stop and then play that file.
But if i modify your code to play previously saved files then it is giving problem with playback in particular case:
1. Start app and start record.
2. Without stopping, close app from background
3. Now start app again.
4. Tap on Play button (I have modified code to enable playbutton always)
5. It won’t play audio. Now if i stop recording from step 2 then it will play recording for next app run.
So you have any solution for this?
Balu M
Author[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord
withOptions:AVAudioSessionCategoryOptionDefaultToSpeaker
error:nil];
Balu M
Author>= IOS 9
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord
withOptions:AVAudioSessionCategoryOptionDefaultToSpeaker
error:nil];
Gill Steens
AuthorIs it possible to save the recorded data and store it in core data?
JKrolling
Authorwould you make a tutorial about how how play music while capturing video ?
rak appdev
Authorthe link is broken. can anyone send the code to [email protected]
Bernard Tai
AuthorDear author,
Even though the article is from 2013….any chance I can still access the file? It’s showing 404….
Vijay Kumar
AuthorIt’s working 🙂
Thanks for sharing this tutorial