How do I record audio on iPhone with AVAudioRecorder?
Actually, there are no examples at all.
Here is my working code. Recording is triggered by the user pressing a button on the navBar.
The recording uses cd quality (44100 samples), stereo (2 channels) linear pcm. Beware: if you want to use a different format, especially an encoded one, make sure you fully understand how to set the AVAudioRecorder settings (read carefully the audio types documentation), otherwise you will never be able to initialize it correctly. One more thing. In the code, I am not showing how to handle metering data, but you can figure it out easily.
Finally, note that the AVAudioRecorder method deleteRecording as of this writing crashes your application. This is why I am removing the recorded file through the File Manager. When recording is done, I save the recorded audio as NSData in the currently edited object using KVC.
#define DOCUMENTS_FOLDER [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]
- (void) startRecording{
UIBarButtonItem *stopButton = [[UIBarButtonItem alloc] initWithTitle:@"Stop" style:UIBarButtonItemStyleBordered target:self action:@selector(stopRecording)];
self.navigationItem.rightBarButtonItem = stopButton;
[stopButton release];
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
NSError *err = nil;
[audioSession setCategory :AVAudioSessionCategoryPlayAndRecord error:&err];
if(err){
NSLog(@"audioSession: %@ %d %@", [err domain], [err code], [[err userInfo] description]);
return;
}
[audioSession setActive:YES error:&err];
err = nil;
if(err){
NSLog(@"audioSession: %@ %d %@", [err domain], [err code], [[err userInfo] description]);
return;
}
recordSetting = [[NSMutableDictionary alloc] init];
[recordSetting setValue :[NSNumber numberWithInt:kAudioFormatLinearPCM] forKey:AVFormatIDKey];
[recordSetting setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];
[recordSetting setValue:[NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey];
[recordSetting setValue :[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];
[recordSetting setValue :[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsBigEndianKey];
[recordSetting setValue :[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsFloatKey];
// Create a new dated file
NSDate *now = [NSDate dateWithTimeIntervalSinceNow:0];
NSString *caldate = [now description];
recorderFilePath = [[NSString stringWithFormat:@"%@/%@.caf", DOCUMENTS_FOLDER, caldate] retain];
NSURL *url = [NSURL fileURLWithPath:recorderFilePath];
err = nil;
recorder = [[ AVAudioRecorder alloc] initWithURL:url settings:recordSetting error:&err];
if(!recorder){
NSLog(@"recorder: %@ %d %@", [err domain], [err code], [[err userInfo] description]);
UIAlertView *alert =
[[UIAlertView alloc] initWithTitle: @"Warning"
message: [err localizedDescription]
delegate: nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
return;
}
//prepare to record
[recorder setDelegate:self];
[recorder prepareToRecord];
recorder.meteringEnabled = YES;
BOOL audioHWAvailable = audioSession.inputIsAvailable;
if (! audioHWAvailable) {
UIAlertView *cantRecordAlert =
[[UIAlertView alloc] initWithTitle: @"Warning"
message: @"Audio input hardware not available"
delegate: nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[cantRecordAlert show];
[cantRecordAlert release];
return;
}
// start recording
[recorder recordForDuration:(NSTimeInterval) 10];
}
- (void) stopRecording{
[recorder stop];
NSURL *url = [NSURL fileURLWithPath: recorderFilePath];
NSError *err = nil;
NSData *audioData = [NSData dataWithContentsOfFile:[url path] options: 0 error:&err];
if(!audioData)
NSLog(@"audio data: %@ %d %@", [err domain], [err code], [[err userInfo] description]);
[editedObject setValue:[NSData dataWithContentsOfURL:url] forKey:editedFieldKey];
//[recorder deleteRecording];
NSFileManager *fm = [NSFileManager defaultManager];
err = nil;
[fm removeItemAtPath:[url path] error:&err];
if(err)
NSLog(@"File Manager: %@ %d %@", [err domain], [err code], [[err userInfo] description]);
UIBarButtonItem *startButton = [[UIBarButtonItem alloc] initWithTitle:@"Record" style:UIBarButtonItemStyleBordered target:self action:@selector(startRecording)];
self.navigationItem.rightBarButtonItem = startButton;
[startButton release];
}
- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *) aRecorder successfully:(BOOL)flag
{
NSLog (@"audioRecorderDidFinishRecording:successfully:");
// your actions here
}
Record the sound through AVAudioRecorder
Once go through below code it might be helpful to you.
First take object for AVAudioRecorder as AVAudioRecorder *audioRecorder;
-(void)viewWillAppear:(BOOL)animated{
NSArray *dirPaths;
NSString *docsDir;
dirPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
//here i took cache directory as saved directory you can also take NSDocumentDirectory
docsDir = [dirPaths objectAtIndex:0];
NSString *soundFilePath = [docsDir stringByAppendingPathComponent:@"sound.caf"];//at this path your recorded audio will be saved
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
NSDictionary *recordSettings = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:AVAudioQualityMin],
AVEncoderAudioQualityKey,
[NSNumber numberWithInt:16],
AVEncoderBitRateKey,
[NSNumber numberWithInt: 2],
AVNumberOfChannelsKey,
[NSNumber numberWithFloat:44100.0],
AVSampleRateKey,
nil];
NSError *error = nil;
audioRecorder = [[AVAudioRecorder alloc]initWithURL:soundFileURL settings:recordSettings error:&error];
if( !audioRecorder ) {
UIAlertView *alert =
[[UIAlertView alloc] initWithTitle: @"Warning" message: [error localizedDescription] delegate: nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
return;
}
if ( error )
{
NSLog( @"error: %@", [error localizedDescription] );
}
else {
[audioRecorder prepareToRecord];
[self recordAudio];//Mehod to Record Audio
}
}
Now define method to record Audio,
-(void) recordAudio
{
if (!audioRecorder.recording)
{
audioRecorder.delegate = self;
[audioRecorder recordForDuration:10];//Here i took record duration as 10 secs
}
}
Now you can write AvAudio record DelegateMethods as,
-(void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully: (BOOL)flag
{
//Your code after sucessful recording;
}
-(void)audioRecorderEncodeErrorDidOccur:(AVAudioRecorder *)recorder error:(NSError *)error
{
NSLog(@"Encode Error occurred");
}
hope it will helps to you...
Using AVAudioRecorder to record voice
AVAudioRecorder does not need anymore the error parameter:
init(URL url: NSURL, settings settings: [String : AnyObject]) throws
Also, I needed to unwrap the filePath, as suggested in a previous answer:
func recordSound(){
let dirPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
let recordingName = "my_audio.wav"
let pathArray = [dirPath, recordingName]
let filePath = NSURL.fileURLWithPathComponents(pathArray)
let recordSettings = [AVEncoderAudioQualityKey: AVAudioQuality.Min.rawValue,
AVEncoderBitRateKey: 16,
AVNumberOfChannelsKey: 2,
AVSampleRateKey: 44100.0]
print(filePath)
let session = AVAudioSession.sharedInstance()
do {
try session.setCategory(AVAudioSessionCategoryPlayAndRecord)
audioRecorder = try AVAudioRecorder(URL: filePath!, settings: recordSettings as! [String : AnyObject])
} catch _ {
print("Error")
}
audioRecorder.delegate = self
audioRecorder.meteringEnabled = true
audioRecorder.prepareToRecord()
audioRecorder.record()
}
How to record audio as mp3 file by using AvAudiorecorder in iOS
Add
[NSNumber numberWithInt:kAudioFormatMPEGLayer3] forKey:AVFormatIDKey
However it's impossible to encode mp3 format at IPhone because of royalty.
Can AVAudioRecorder be used to record audio coming from your iOS app?
As far as I can tell, there's no way to do this with AVAudioRecorder. You must use Audio Units.
Record audio iOS
Is there a way to record device audio on the iPhone?
Record samples being played with OpenAL
Offline audio recording on iOS with OpenAL
Related Topics
Ansible Regex_Findall Multiple Strings
React Native App Works on Debug Mode, But Not Works Release Mode on Ios
Uistackview Hiding/Unhiding Arrangedsubview Issue
Open Facebook Page in Native Facebook iOS App Via Simple Url Sheme Issue
Remove Alpha Channel in an Image
Swift - Integer Conversion to Hours/Minutes/Seconds
Cell Size Not Updating After Changing Flow Layout'S Itemsize
How to Get the Root Directory of My iOS App
Wkwebview Not Loading Webpage - Renders Blank Screen in Swift
How to Center Horizontally Uicollectionview Cells
How to Create a Custom Pop Up View With Swift
Iphone/Ipad: How to Make Uitextfield Readonly (But Not Disabled)
Uiimageview - How to Get the File Name of the Image Assigned
How to Load Image from Local Path iOS Swift (By Path)
Take Screenshots in the iOS Simulator
Detect Tap on a Button in Uitableviewcell for Uitableview Containing Multiple Sections
Swift Parse Json - the Data Couldn'T Be Read Because It Isn'T in the Correct Format