How to Record and Play Audio With AVFoundation Framework in IOS?

Hey everyone as we have already created an application using AvFoundation library. Similar to this, we will be using the same library to create our own custom through which we can play and record an audio file. In this tutorial, I am going to walk you through the basics of this framework and show you how to manage audio playing, as well as, recording.

To provide you with an example, I will build a simple audio application that allows users to record and play audio. In this tutorial, my primary focus is to demonstrate the AV Foundation framework so the user interface of our application is very simple.

The AVFoundation provides easy ways to deal with audio. In this tutorial, we will be going to deal with these two classes:

AVAudioPlayer – An audio player for playing audio files. By using the player, the user can play sounds of any duration and in any audio format like- mp3 etc available in iOS.

AVAudioRecorder – An audio recorder for recording audio within the application.

Initial Setup

First of all, we will be going to run the XCode and then we need to click on the create new application button. Later on, we need to select the single view application as shown below.

Now after this step, we will be going to give a name to our application. For my application, I will name it as “AudioRecordingSample”.

Adding AVFoundation Framework

By default, the AVFoundation framework is not included in any Xcode project. So, we need to add it manually. In the Project Navigator of the application, select the “AudioRecordingSample” project.

In the Content Area, select “AudioRecordingSample” under Targets and click “Build Phases”. Expand “Link Binary with Libraries” and click on the “+” button to add the “AVFoundation.framework” to your project.

Here is the snapshot to which I am adding AVFoundation Framework.

To use the AVAudioPlayer and AVAudioRecorder class and its features, we need to import it in ViewController.h.

Interface Designing

Here, we will be going to design a simple yet attractive interface for our application. This will consist of three things here:

A button through which we will be going to play the audio from the application through AV Library and will name it as the Record button. Now set the constraints to it as Top layout, center horizontal, equal width and equal height.

A second button just below the first button through which we will be going to stop the recording after we finish. Here set the constraints to Top to button 1 and center horizontally, equal width and equal height to button 1.

The third button below the second stop button, through which we will be going to record the audio in the application. In this area, set the constraints as top to button second, center horizontally and equal width, equal height with the second button.

After performing all the steps in designing your view will looks similar to this as shown below.

Connections With Outlets

Now we need to create a connection between the outlets and objects with the view controller so that we can use them to perform some functionality later in our app. First, we need to connect all the three buttons simultaneously and then later will going to create their actions in the application as well.

Head to the view controller.h file of the application and add the given line of code to it:

Initializing 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.m file. I will be going to explain both delegates as we move forward in the application development.

In the above code, we first define the sound file URL for saving the recording and then configure the audio session later on. iOS itself will be going to handle the audio behavior of an app by using audio sessions. Also, we are hiding the two buttons which are play and stop button at initial launch so the user will not get confused with the buttons.

When the app will launch, it automatically gets an audio session. You can grab the particular session by calling [AVAudioSession sharedInstance] and configure it according to requirement. Here, we tell iOS that the app uses “AVAudioSessionCategoryPlayAndRecord” category which will be going to enables both audio input and output. We start and enable the audio recorder by calling “prepareToRecord:” method in the view did load part of the viewcontroller.

Implementing Record Button

Now we have completed the audio preparation. Let’s now move on to implement the action method of the Record button. Before we get into the code, let me tell you how the “Record” button works.

When the user taps the “Record” button, the app will start recording and the button text will be changed to “Pause”. If the user taps the “Pause” button, the recording will pause until the “Record” button is tapped again. The audio recording will only be stopped when the user taps the “Stop” button.

In the above code, we will check whether the audio player is playing or not. If audio player is playing the audio, we simply stop it by using the “stopAction:” method. The above code tells the user if the app is in the recording mode or not. If it’s not in a recording mode, the app will be going to activates the audio sessions and starts the recording. To make the recording to work (or sound to play), the audio session of the application must be active.

In short, you can use the following methods of AVAudioRecorder to control the recording of the app:

record – start and resume a recording

pause –can pause a recording

stop – can stop a recording

Stopping the Recording

For the Stop button, we will be using the “stop:” method of the recorder, through which we can deactivate the audio session. Edit the “stopAction:” method by using the following code:

Time to Call AVAudioRecorderDelegate Protocol

Now we will be going to use the AVAudioRecorderDelegate protocol to handle the interruptions occured within the audio (for example, a phone call during audio recording) and the completion of recording. In this example, the ViewController is the delegate. The methods defined in AVAudioRecorderDelegate protocol are optional and is dependent on us.

Here, we will only implement the “audioRecorderDidFinishRecording:” method to handle the completion of recording. Add the following code to ViewController.m:

After finishing the recording, we can simply change the “Pause” button back to “Record” button.

The above code is very simple. Normally, there are few points needs to be configured an audio player:

Initialize the audio play and add or assign a sound file to it. Here it is the audio file of the recording.

Give a path of an audio player delegate object, which can handles error during the recording as well as the playback-completed event.

This will be going to use the playAudio: method to play the sound file.

Implementing the AVAudioPlayerDelegate Protocol

This delegate of an AVAudioPlayer object which is AVAudioPlayerDelegate protocol. This delegate allows us to handle interruptions, audio decoding errors and will be going to updates the user interface when an audio has finished playing. All methods in AVAudioplayerDelegate protocol are optional.

Let see how it works, We are going to implement the “audioPlayerDidFinishPlaying:” method to display an alert message after the audio recording has stopped playing.

Run the Build and See the Action

We will now be going to run and test whether the audio is working fine or not on a physical device or software simulator. If you are using an actual device like iPhone, the audio being recorded comes from the device connected to the built-in microphone or headset of the device. If you are testing the application with Simulator, the audio will come from the system’s default audio input device as set in the System Preference.

So let’s compile and run the app. In the First launch, you will see the record button only as we have to hide the other buttons at initial launch so don’t panic wait for some time.

Now Tap “Recording Button” to start recording. Say something, tap the “Stop” button and then select the “Play” button to listen to the playback.

Now after you will tap on recording button then it will display other two buttons which are “stop” and “play” button as you can see below.

Summing Up

I hope this blog will serve you what you have expected according to its title. Remember, this library is quite useful in the form of multimedia and audio, video features and is able to provide you a vast variety of features in iOS. If you like this tutorial and want more tutorial similar to this then let me know below in the comments.

I am working as an ios developer and having experience in objective c with more then 2 live project.Implementing facebook login, google login, parsing json and soap services, storyboard designing using auto layout.