Why is AVAudioRecorder prepareToRecord Failing? - iphone

I am trying to setup a basic controller that will record user audio input(voice). However, the AVAudioRecorder's prepareToRecord method is failing and I can't figure out why. I have setup the audio session in my app delegate and I do not receive an errors when I instantiate the AVAudioRecorder instance:
// App delegate snippet
AVAudioSession* audioSession = [AVAudioSession sharedInstance];
NSError* audioSessionError = nil;
[audioSession setCategory: AVAudioSessionCategoryPlayAndRecord
error: &audioSessionError];
if (audioSessionError) {
NSLog (#"Error setting audio category: %#", [audioSessionError localizedDescription]);
} else {
NSLog(#"No session errors for setting category");
}
[audioSession setActive:YES error:&audioSessionError];
if (audioSessionError) {
NSLog (#"Error activating audio session: %#", [audioSessionError localizedDescription]);
} else {
NSLog(#"no session errors for setActive");
}
// VIEW DID LOAD IN RECORDERCONTROLLER
- (void)viewDidLoad {
self.navigationItem.title = [NSString stringWithFormat:#"%#", [[MyAppDelegate loadApplicationPlist] valueForKey:#"recorderViewTitle"]];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone
target:self
action:#selector(dismiss)];
[self alertIfNoAudioInput];
[self createAVAudioRecorder];
minutesSecondsFormatter = [[SimpleMinutesSecondsFormatter alloc] init];
currentTimeUpdateTimer = [NSTimer scheduledTimerWithTimeInterval:0.1
target:self selector:#selector(updateAudioDisplay)
userInfo:NULL repeats:YES];
[super viewDidLoad];
}
// CREATE AVAUDIORECORDER
- (NSError *)createAVAudioRecorder {
NSError *recorderSetupError = nil;
[audioRecorder release];
audioRecorder = nil;
NSString *timestamp = [NSString stringWithFormat:#"%d", (long)[[NSDate date] timeIntervalSince1970]];
NSString *destinationString = [[MyAppDelegate getAppDocumentsDirectory] stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.caf", timestamp]];
NSLog(#"destinationString: %#", destinationString);
NSURL *destinationUrl = [NSURL fileURLWithPath: destinationString];
audioRecorder = [[AVAudioRecorder alloc] initWithURL:destinationUrl
settings:[[AVRecordSettings sharedInstance] getSettings]
error:&recorderSetupError];
if (recorderSetupError) {
UIAlertView *cantRecordAlert =
[[UIAlertView alloc] initWithTitle:#"Can't record"
message:[recorderSetupError localizedDescription]
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[cantRecordAlert show];
[cantRecordAlert release];
return recorderSetupError;
} else {
NSLog(#"no av setup error");
}
if ([audioRecorder prepareToRecord]) {
recordPauseButton.enabled = YES;
audioRecorder.delegate = self;
} else {
NSLog(#"couldn't prepare to record");
}
NSLog (#"recorderSetupError: %#", recorderSetupError);
return recorderSetupError;
}

The prepareToRecord also fails (silently, without an error) if the directory where you try to save the file doesn't exist. Use NSFileManager to check if the directory already exists.

It is failing because you did not initialize the AVAudioRecorder object using proper settings. Do this before initializing it:
NSDictionary *recordSettings =
[[NSDictionary alloc] initWithObjectsAndKeys:
[NSNumber numberWithFloat: 44100.0], AVSampleRateKey,
[NSNumber numberWithInt: kAudioFormatAppleLossless], AVFormatIDKey,
[NSNumber numberWithInt: 1], AVNumberOfChannelsKey,
[NSNumber numberWithInt: AVAudioQualityMax], AVEncoderAudioQualityKey,
nil];
then you can instantiate it using
audioRecorder = [[AVAudioRecorder alloc] initWithURL:destinationUrl
settings:recordSettings
error:&recorderSetupError];

Related

iOS - Overwrite the particular audio recording In specific time

Hi I need to develop an app that can record, play, stop and overwrite audio. I have done the Recording by using AvAudioRecorder:
NSDictionary *audioSettings = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithFloat: 44100],AVSampleRateKey,
[NSNumber numberWithInt: kAudioFormatLinearPCM],AVFormatIDKey,
[NSNumber numberWithInt: 2],AVNumberOfChannelsKey,
[NSNumber numberWithInt: AVAudioQualityLow], AVEncoderAudioQualityKey,
nil];
self.audioRecorder = [[AVAudioRecorder alloc]
initWithURL:audioFileURL
settings:audioSettings
error:nil];
[sliderTimer invalidate];
[self.audioRecorder record];
sliderTimer = [NSTimer scheduledTimerWithTimeInterval:0.2
target:self
selector:#selector(updateSlider)
userInfo:nil repeats:YES];
...and playback is done using AVplayer.
But I dont know how to overwrite the recording. This the outline of my overwrite implementation:
Stop Recording
Move the slider position to the particular point
Then, start recording.
This is the functionality to overwrite the previous recordings.
So, As per the steps I have written
[self.audioRecorder stop];
[[self audioSlider] setValue:self.audioSlider.value animated:YES];
[self.audioRecorder recordAtTime:self.audioSlider.value forDuration:self.audioSlider.maximumValue];
...but its not working. Instead, they totally re-record the file. Could any body help me for this critical situation.
Create audioSession object,its upto you whether you want to activate or deactivate your app’s audio session.(AVAudioSession)
audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory :AVAudioSessionCategoryPlayAndRecord error:&err];
if(err) {
NSLog(#"audioSession: %# %d %#", [err domain], [err code], [[err userInfo] description]);
return;
}
[audioSession setActive:YES error:&err];
Start recording proces,
-startRecording
{
[recordSetting setValue :[NSNumber numberWithInt:kAudioFormatAppleIMA4] forKey:AVFormatIDKey];
// We can use 44100, 32000, 24000, 16000 or 12000 depending on sound quality
[recordSetting setValue:[NSNumber numberWithFloat:32000.0] forKey:AVSampleRateKey];
// We can use 2(if using additional h/w) or 1 (iPhone only has one microphone)
[recordSetting setValue:[NSNumber numberWithInt: 1] forKey:AVNumberOfChannelsKey];
mediaPath = [[NSString stringWithFormat:#"%#/myVoice.mp3", DOCUMENTS_FOLDER] retain];//where you want to save your recorded audio.
NSURL *url = [NSURL fileURLWithPath:mediaPath];
err = nil;
NSData *audioData = [NSData dataWithContentsOfFile:[url path] options: 0 error:&err];
recorder = [[ AVAudioRecorder alloc] initWithURL:url settings:recordSetting error:&err];
[recorder setDelegate:self];
[recorder prepareToRecord];
recorder.meteringEnabled = YES;
BOOL audioHWAvailable = audioSession.inputAvailable;
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;
}
[recorder record];
}
Pause recording:
-pauseRecording
{
[recorder pause];
//[recorder updateMeters];
}
Again resume the process..audiosession will do it for you...
-resumerecording
{
[recorder record];
//[recorder updateMeters];
}
EDIT: [recorder updateMeters]; should be called periodically which refreshes the average and peak power values for all channels of an audio recorder.
You can use timer for that.
For example:
NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:#selector(updateAudioDisplay) userInfo:NULL repeats:YES];
-(void)updateAudioDisplay
{
if (!recorder.isRecording)
{
[recorder updateMeters];
}
else
{
if (recorder == nil) {
//recording is not yet started
}
else
{
//paused
}
}
}
You can download the sample code from here.

Re-recording with AVAudioRecorder

I can record with the setup below - it works first time, but then when I try again the file is always 8192 bytes, i.e. not a correct recording.
-(void) startRecording
{
NSDictionary *settings = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithFloat: 11025.0f], AVSampleRateKey,
[NSNumber numberWithInt: kAudioFormatMPEG4AAC], AVFormatIDKey,
[NSNumber numberWithInt: 2], AVNumberOfChannelsKey,
[NSNumber numberWithInt: AVAudioQualityLow], AVEncoderAudioQualityKey,
nil];
NSString *filenameBasedOnTime = [[NSDate date] description];
if (_recordedFileURL) _recordedFileURL = nil;
_recordedFileURL = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingString:filenameBasedOnTime]];
NSError* error;
if (_audioRecorder) _audioRecorder = nil;
_audioRecorder = [[AVAudioRecorder alloc] initWithURL:_recordedFileURL settings:settings error:&error];
_audioRecorder.delegate = self;
if (error)
{
return;
}
[_audioRecorder prepareToRecord];
_audioRecorder.meteringEnabled = YES;
[_audioRecorder record];
}
-(void) stopRecord
{
[_audioRecorder stop];
}
- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag
{
[self saveRecording];
}
-(void) saveRecording
{
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:_recordedFileURL.relativeString]];
NSLog(#"Recording data size = %i", [data length]);
}
It is called inside a UIPopoverController if that helps...
Since found out that the problem was I was missing
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:NULL];
From here iPhone SDK: AVAudioRecorder will not record after calling [AVPlayer play]

Received memory warning in recording the video

I made an app for ipad which contains image dragging and video recording.
It takes screenshots as recording starts and after that makes movie by appending them.
When i record video of 5 to 10 seconds , it works fine. But as i try to record video of 1 minute or more, it crashes and gives "Received memory warning" in log.
I have used the following code ;
- (IBAction)btnRecording_Pressed:(id)sender
{
if ([recordButton.titleLabel.text isEqualToString:#"Start Recording"]) {
backButton.enabled = NO;
[recordButton setTitle:#"Stop Recording" forState:UIControlStateNormal];
fileIndex = 0;
recTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/5.0 target:self selector:#selector(startFrameCapture) userInfo:nil repeats:YES];
[recTimer retain];
[self startRecording];
}else{
[recordButton setTitle:#"Start Recording" forState:UIControlStateNormal];
[recTimer invalidate];
[recTimer release];
[self stopRecording];
[self getFileName];
}
}
-(void)startFrameCapture
{
fileIndex++;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
documentsDirectory = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"Screenshot%d.jpg",fileIndex]];
[self performSelectorInBackground:#selector(newThread:) withObject:documentsDirectory];
}
-(void)newThread:(NSString *)frameName{
if ([[UIScreen mainScreen] respondsToSelector:#selector(scale)])
UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, NO, [UIScreen mainScreen].scale);
else
UIGraphicsBeginImageContext(self.view.bounds.size);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
imageData = UIImageJPEGRepresentation(viewImage, 1.0);
[imageData writeToFile:frameName atomically:YES];
}
- (void) startRecording{
if([recorder isRecording]){
NSLog(#"Stopped Recording");
[self stopRecording];
}else{
NSLog(#"Started Recording");
[self prepareRecorderNow];
[recorder record];
}
}
- (void) stopRecording{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
if([recorder isRecording]){
[recorder stop];
[recorder release];
recorder = nil;
}
[pool drain];
}
-(void)prepareRecorderNow{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
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] 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
[recorderFilePath release];
recorderFilePath = [[NSString stringWithFormat:#"%#/deformed.caf", DOCUMENTS_FOLDER] retain];
NSURL *url = [NSURL fileURLWithPath:recorderFilePath];
err = nil;
recorder = [[ AVAudioRecorder alloc] initWithURL:url settings:recordSetting error:&err];
[recordSetting release];
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;
}
NSLog(#"Not Over Man");
[pool drain];
}
What can be the issue ?
Thanks!!
You are creating a image context 5 times per second. That could be the problem.
Try reusing your UIGraphicsImageContext by saving it as an ivar or property.
I had a similar problem in case of Capturing Pictures, practically, I have seen the problem with the NOT RELEASED UIImage objects, which occupies most of the memory, here is a fix you can try
-(void)newThread:(NSString *)frameName
{
UIImage *viewImage=nil;
viewImage=[[UIImage alloc] init];
if ([[UIScreen mainScreen] respondsToSelector:#selector(scale)])
UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, NO, [UIScreen mainScreen].scale);
else
UIGraphicsBeginImageContext(self.view.bounds.size);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
imageData = UIImageJPEGRepresentation(viewImage, 1.0);
[imageData writeToFile:frameName atomically:YES];
[viewImage release];
}

how to record voice and play in iphone

I have implemented voice recording functionality in our project but i couldn't have control on stop and discard buttons. In second time not able to record the voice after clicking the discard button.
After clicking discard also the audio file is playing and not able to click start button again.
Please help on this one
Here is the source code
.h file
#interface VoiceInput : UIViewController
<AVAudioRecorderDelegate>
{
//Audio record
float remainingDelayTime;
float remainingRecordTime;
UILabel *delayLabel;
UIProgressView *progressView;
AVAudioRecorder *recorder;
NSTimer *delayTimer;
NSTimer *recordTimer;
BOOL toggle;
NSURL *recordedTmpFile;
NSError *error;
}
#property (nonatomic, retain) AVAudioRecorder *recorder;
#property (nonatomic, retain) NSTimer *delayTimer;
#property (nonatomic, retain) NSTimer *recordTimer;
#end
.m file
#implementation VoiceInput
#synthesize progressView;
#synthesize recorder;
#synthesize delayTimer;
#synthesize recordTimer;
- (void)viewDidLoad
{
toggle = YES;
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:&error];
[audioSession setActive:YES error:&error];
}
-(void)startPushed
{
if (toggle)
{
remainingDelayTime = 4.0;
delayTimer = [NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:#selector(delayTimerFired:)
userInfo:nil
repeats:YES];
toggle = NO;
NSMutableDictionary *rs = [[NSMutableDictionary alloc] init];
[rs setValue:[NSNumber numberWithInt:kAudioFormatAppleIMA4] forKey:AVFormatIDKey];
[rs setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];
[rs setValue:[NSNumber numberWithInt:2] forKey:AVNumberOfChannelsKey];
recordedTmpFile = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:#"%.0f.%#", [NSDate timeIntervalSinceReferenceDate] * 1000.0, #"caf"]]];
NSLog(#"USING FILE CALLED: %#", recordedTmpFile);
recorder = [[AVAudioRecorder alloc] initWithURL:recordedTmpFile settings:rs error:&error];
[recorder setDelegate:self];
[recorder prepareToRecord];
[recorder record];
}
else
{
toggle = YES;
NSLog(#"Using File Called: %#", recordedTmpFile);
[recorder stop];
}
self.discardButton.enabled = NO;
self.startButton.enabled = NO;
self.stopButton.enabled = YES;
}
-(void)stopPushed
{
if([self.recorder isRecording])
{
[self.recorder stop];
if(remainingRecordTime >= 1.0)
{
[self.recordTimer invalidate];
}
}
self.delayLabel.textColor = [UIColor darkGrayColor];
self.delayLabel.text = [[NSString alloc] initWithFormat:#"Record in ..."];
self.discardButton.enabled = YES;
self.playbackButton.enabled = YES;
self.startButton.enabled = NO;
self.stopButton.enabled = NO;
}
-(void)playbackPushed
{
AVAudioPlayer *avPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:recordedTmpFile error:&error];
[avPlayer prepareToPlay];
[avPlayer play];
self.discardButton.enabled = YES;
self.playbackButton.enabled = YES;
self.returnButton.enabled = YES;
self.startButton.enabled = YES;
self.stopButton.enabled = YES;
}
-(void)discardPushed
{
[self.recorder deleteRecording];
self.progressView.progress = 0;
self.delayLabel.textColor = [UIColor darkGrayColor];
self.delayLabel.text = #"Record in ...";
self.discardButton.enabled = NO;
self.playbackButton.enabled = NO;
self.startButton.enabled = YES;
self.stopButton.enabled = YES;
}
-(void)delayTimerFired:(NSTimer *)theDelayTimer
{
self.progressView.progress = 0;
remainingDelayTime -= 1.0;
NSLog(#"fired %f", remainingDelayTime);
self.delayLabel.textColor = [UIColor blackColor];
self.delayLabel.text = [[NSString alloc] initWithFormat:#"Record in %2.0f",
remainingDelayTime];
if(remainingDelayTime <= 0.0)
{
[self.delayTimer invalidate];
self.delayLabel.text = [[NSString alloc] initWithFormat:#"Recording"];
[self.recorder recordForDuration:TIME];
remainingRecordTime = TIME;
recordTimer = [NSTimer scheduledTimerWithTimeInterval:TIME_DECREMENT
target:self
selector:#selector(recordTimerFired:)
userInfo:nil
repeats:YES];
}
}
-(void)recordTimerFired:(NSTimer *)theRecordTimer
{
remainingRecordTime -= TIME_DECREMENT;
NSLog(#"fired %f", remainingRecordTime);
self.progressView.progress = (TIME - remainingRecordTime)/TIME;
if(remainingRecordTime <= 0.0)
{
[self.recordTimer invalidate];
}
}
Thanks in advance
Have a look on this.You can Start recording by this :-
- (void) startRecording
{
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
NSError *err = nil;
[audioSession setCategory :AVAudioSessionCategoryPlayAndRecord error:&err];
[audioSession setMode:AVAudioSessionModeVoiceChat 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];
// We can use kAudioFormatAppleIMA4 (4:1 compression) or kAudioFormatLinearPCM for nocompression
[recordSetting setValue :[NSNumber numberWithInt:kAudioFormatAppleIMA4] forKey:AVFormatIDKey];
// We can use 44100, 32000, 24000, 16000 or 12000 depending on sound quality
[recordSetting setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];
// We can use 2(if using additional h/w) or 1 (iPhone only has one microphone)
[recordSetting setValue:[NSNumber numberWithInt: 1] forKey:AVNumberOfChannelsKey];
[recordSetting setObject:[NSNumber numberWithInt:12800] forKey:AVEncoderBitRateKey];
[recordSetting setObject:[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];
[recordSetting setObject:[NSNumber numberWithInt: AVAudioQualityMax] forKey: AVEncoderAudioQualityKey];
NSString *str;
str = [NSString stringWithFormat:#"%#/MySound.caf",DOCUMENTS_FOLDER];
NSLog(#"recorderFilePath: %#",str);
NSURL *url = [NSURL fileURLWithPath:str];
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];
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];
return;
}
// start recording
[recorder recordForDuration:(NSTimeInterval) 20];
}
This will start your recording.After it you can stop recording :-
- (void) stopRecording
{
[recorder stop];
}
Now you can play your recording by this :-
- (void)playRecordingSound
{
if(!recorderFilePath)
recorderFilePath = [NSString stringWithFormat:#"%#/MySound.caf", DOCUMENTS_FOLDER] ;
if(soundID)
{
AudioServicesDisposeSystemSoundID(soundID);
}
//Get a URL for the sound file
NSURL *filePath = [NSURL fileURLWithPath:recorderFilePath isDirectory:NO];
//Use audio sevices to create the sound
AudioServicesCreateSystemSoundID((__bridge CFURLRef)filePath, &soundID);
//Use audio services to play the sound
AudioServicesPlaySystemSound(soundID);
}
Hope it helps Thanks :)

Reduce Noise While Recording users Voice in iphone Application?

I am trying to record users voice with background music playing behind. I am able to set a session and play background and record concurrently using AVAudioSessionCategoryPlayAndRecord. But it's recording lot's of noice,
Does any one have an idea how to reduce the noise?
#define DOCUMENTS [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]
#define PATH_ARQUIVO [DOCUMENTS stringByAppendingPathComponent:#"gravacao.ma4"]
-(IBAction) recordAudio:(UIButton *)sender {
NSURL* urlArquivo = [[NSURL alloc] initFileURLWithPath:PATH_ARQUIVO];
NSDictionary *dic = [[NSDictionary alloc] initWithObjectsAndKeys:
[NSNumber numberWithInt:AVAudioQualityMin], AVEncoderAudioQualityKey,
[NSNumber numberWithInt:16], AVEncoderBitRateKey,
[NSNumber numberWithInt:2], AVNumberOfChannelsKey,
[NSNumber numberWithFloat:44.1], AVSampleRateKey,
nil];
NSError* error;
self.audioRecorder = [[AVAudioRecorder alloc] initWithURL:urlArquivo settings:dic error:&error];
if (error) {
NSLog(#"error: %#", [erro localizedDescription]);
} else {
//buffering
[self.audioRecorder prepareToRecord];
//recording
[self.audioRecorder record];
}
}
-(IBAction) stopRecorder:(UIButton *)sender {
if ([self.audioRecorder isRecording]) {
[self.audioRecorder stop];
}
}
-(IBAction) PlayAudio:(UIButton *)sender {
NSURL* urlArquivo = [[NSURL alloc] initFileURLWithPath:PATH_ARQUIVO];
NSError* error;
self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:urlArquivo error:&error];
if (erro) {
NSLog(#"error %#", [error localizedDescription]);
} else {
self.audioPlayer.numberOfLoops = HUGE_VALF;
self.audioPlayer.enableRate = YES;
[self.audioPlayer prepareToPlay];
[self.audioPlayer play];
}
}
-(IBAction) stopPlaying:(UIButton *)sender {
if ([self.audioPlayer isPlaying]) {
[self.audioPlayer stop];
}
}
-(IBAction) changeRate:(UISlider *)sender {
self.audioPlayer.rate = sender.value * 2;
/* it's a UISlider, max value = 1, min = 0 */
}