Hands-on coding demo on using AVAudioRecorder to record audio from the device's built-in microphone and saving to the file system
- [Narrator] To begin recording audio using AVAudioRecorder, let's first go to the class AudioViewController, found in our project. As we can see here, I've given us two buttons, a Record button and a Play button. Scrolling down, I've also created two corresponding action functions, recordButtonPressed and playButtonPressed. Our objective here is to create our AVAudioRecorder object and implement the necessary functions so that we can trigger recording by pressing the Record button.
Playing back our recordings will come in the next lesson. Let's gets started. The first thing we want to do is declare our recorder object. Next, let's jump down here, and I'm going to mark off a section, and we're going to call it Helpers. We're going to create a few helper functions. As we remember, when creating an AVAudioRecorder object, we initialize it with two properties, a file URL and a settings dictionary. These functions that we're going to create will return those values.
So first, we're going to start with the file URL. Let's create a function called audioFileLocation. This function will simply return a string value that contains the path to the temporary directory, and we'll append our file name. This gives us a direct path to the file which we are recording. Next, we'll create a function called audioRecorderSettings that returns a dictionary of keys which will be used to determine the recording settings of our AVAudioRecorder object.
Let's start by creating our dictionary, which we're going to call settings. And so, in this dictionary, we're going to go and input the different keys that we want to have settings for. The first one is going to be the format, and that key is AVFormatIDKey. And the value that we're going to give it is going to be kAudioFormatAppleLossless. The next key that we want to do is our sample rate, so we're going to say AVSampleRateKey, and that value is going to be 44100.
Next, we're going to input AVNumberOfChannelsKeys, which is the property that we're going to set that determines the number of channels we're going to be recording, and we're going to be recording one. We're going to want to set the bit depth, so that key is AVLinearPCMBitDepthKey, and we're going to give that a value of 16. The last key that we're going to enter in here is AVEncoderAudioQualityKey, which is exactly what the key says, it's the quality of audio we're going to be recording.
And the value that we're going to set for that is AVAudioQuality.high. We want the raw value of that. Now we just have to return our settings dictionary. Now, we'll create a function called prepareAudioRecorder, and in this function, we take the necessary steps to prepare our AVAudioRecorder for recording.
So I'm going to come up over here, I'm going to mark out another section, and we're going to call it Main. And in here, we're going to create our function prepareAudioRecorder. In this function, the first thing that we want to do is grab the shared instance of AVAudioSession, which is the singleton that is managing all of the audio throughout the device. So we'll say let audioSession equal AVAudioSession.sharedInstance.
And now that we have that, we're going to go and open up a do because we're going to try a few things. We're going to try audioSession.setCategory, which is going to throw, and the category that we want to set is AVAudioSessionPlayAndRecord. While we're here, we also want to try to initialize our AVAudioRecorder. So we'll say try audioRecorder equals AVAudioRecorder, and we're going to choose it with URL and settings.
Now, this is where our helper functions are going to come into play. So, for the URL, we're going to say URL fileURLwithPath self.audioFileLocation. And we'll close that out. And then for settings, we'll say self.audioRecorderSettings. And then because we were trying, we have to put a catch clause in here.
And the catch, we're just going to print that error, in case we come across one. Last thing that we want to do in here, is we want to say audioRecorder.prepareToRecord, and that takes care of our prepareToAudio function. Next, let's call our prepareAudioRecorder function in viewDidLoad. The first helper function that I want to create is called updateRecordButtonTitle, which will do just that.
When called, it'll determine whether or not the audio recorder is recording and will update the title property of the button accordingly. So let's go ahead and create that. So if the audio recorder is recording, we're going to set the title to be Recording. And if it isn't, we'll set the title as Record. The last function we're going to create is called verifyFileExists, which will simply verify if the recording file exists after we finished recording.
This will give us a way to determine that our recording was successful. So this function creates a default fileManager, and that fileManager simply checks to see if a file exists at the audio file location path that we have generated, and if so, we'll handle that accordingly. The last thing we need to do is come over to our recordButtonPressed action function and write in the logic to determine what happens when we press the record button.
Let's go ahead and get that function in highlight. Let's go ahead and write in our logic. If audioRecorder.isRecording. So if audioRecorder is not recording, we're going to say, start recording. And if it is recording, then we want to stop recording. So this is how we're going to implement this logic. First, we're going to have to grab our AVAudioSession shared instance again.
And now I'm going to go ahead and open up a do clause. And we'll say try audioSession.setActive true, and then we also want to set our audioRecorder to start recording. Now, for us to stop recording, it's simply audioRecorder stop, and then we want to grab our AVAudioSessons shared instance again, and what we want to do now is inactivate our audio session from the app.
So we're going to say try audioSession.setActive false. Then, because we're stopping a recording, is we want to verify that this all worked. So we want to do a check. And to do our check, we'll just say if self.verifyFileExists, so we're going to check against this function that we have, and if so, we're going to say print, file exists.
And we also want to take our play button, and we want to unhide it from our user, so that they can actually go and play. So we're just going to say false, and if the file doesn't exist, we're going to inform ourselves by saying, there was a problem recording. Now the last thing we need to do in this function is update our record button's title, so we'll say self.updateRecordButtonTitle. Now that we have this all in here, let's go ahead and run it on our device to see what we have.
I'm going to jump into the audio recorder, and I'm going to click the Record Audio button. As we can see, the button title updates, and we see it says Recording, and it is recording our audio now. And then when I press it again, it's going to stop. It runs the check to see if the file exists, and because it does, we now have a Play button, so that we can play back our audio. Now that we've confirmed that we're able to record our file, let's move on to the next lesson, where we discuss playing back the file that we just created.
- Concurrent programming with AVFoundation
- Recording audio with AVAudioRecorder
- Playing audio with AVAudioPlayer
- Recording movies with AVCaptureSession
- Adding overlays and text to videos
- Exporting video