FRAMEWORK IN IOS?
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.
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:
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@property (strong, nonatomic) IBOutlet UIButton *Play;
- (IBAction)playAction:(UIButton *)sender;
@property (strong, nonatomic) IBOutlet UIButton *stop;
- (IBAction)stopAction:(UIButton *)sender;
@property (strong, nonatomic) IBOutlet UIButton *record;
- (IBAction)recordAction:(UIButton *)sender;
@end
[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES) lastObject],
@"MyAudioMemo.m4a",
nil];
NSURL *outputFileURL = [NSURL
fileURLWithPathComponents:pathComponents];
// Setup audio session
AVAudioSession *session = [AVAudioSession sharedInstance];
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.
Edit the “recordAction:” method with the following code:
- (IBAction)recordAction:(UIButton *)sender {
if (player.playing) {
[player stop];
}
if (!recorder.recording) {
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setActive:YES error:nil];
// Start recording
[recorder record];
[self.record setTitle:@"Pause" forState:UIControlStateNormal];
} else {
// Pause recording
[recorder pause];
[self.record setTitle:@"Record"
forState:UIControlStateNormal];
}
[self.stop setHidden:NO];
[self.Play setHidden:NO];
}
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:
- (IBAction)stopAction:(UIButton *)sender {
[recorder stop];
AVAudioSession *audioSession = [AVAudioSession
sharedInstance];
[audioSession setActive:NO error:nil];
}
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.
- (void) audioRecorderDidFinishRecording:(AVAudioRecorder
*)avrecorder successfully:(BOOL)flag{
[self.record setTitle:@"Record" forState:UIControlStateNormal];
[self.stop setHidden:NO];
[self.Play setHidden:NO];
}
PLAYING SOUND USING AVAUDIOPLAYER
Finally, we are at the point where we can implement the “Play”
button for audio playback using AVAudioPlayer. In the
ViewController.m, edit the “playAction:” button method using the
following code:
- (IBAction)playAction:(UIButton *)sender {
if (!recorder.recording){
player = [[AVAudioPlayer alloc]
initWithContentsOfURL:recorder.url error:nil];
[player setDelegate:self];
[player play];
}
}
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.
Add the following code in ViewController.m:
- (void) audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:
(BOOL)flag{
UIAlertController *alertPrompt = [UIAlertController
alertControllerWithTitle:@"Completed" message:@"The Recording has been
Finished" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *action = [UIAlertAction actionWithTitle:@"Okay"
style:UIAlertActionStyleCancel handler:nil];
[alertPrompt addAction:action];
[self presentViewController:alertPrompt animated:YES completion:nil];
}
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.
Until next time.!! Keep learning and keep coding.!!!
Connect with source url:-
https://www.loginworks.com/blogs/record-play-audio-
avfoundation-framework-ios/