Record and Play using AVAudioRecorder and AVAudioPlayer - iphone

I am creating an app in which user can record and play the recorded file.
I am able to record and play as well, but the problem I am facing is that while playing(listening) the recording, if user presses the record button it will start recording and pressing on the stop resumes the previous recording where it was left.
What I want is when user is listening to the recording and in the mean while he presses the record button, then the last recording (which he was playing) should get destroyed.
In short,I do not want to resume the last recording, I want to play the recent recording.
Here is my code for recording and playback.
-(void)showStopbutton
{
if (flag_for_mic_button == 0)
{
// All in vain the following condition not making any effect palyer is resuming back
if ([audioPlayer isPlaying])
{
[audioPlayer stop];
audioPlayer = nil;
audioPlayer = NO;
}
//
[btn_Mic setImage:[UIImage imageNamed:#"stop.png"] forState:UIControlStateNormal];
lbl_Press.hidden = TRUE;
lbl_updateTime.hidden = FALSE;
[self startRecording];
flag_for_mic_button = 1;
}
else if (flag_for_mic_button ==1)
{
[self stopRecording];
// All in vain the following condition not making any effect palyer is resuming back
if ([audioPlayer isPlaying])
{
audioPlayer = NO;
[audioPlayer stop];
audioPlayer = nil;
}
//
[btn_Mic setImage:[UIImage imageNamed:#"mic.png"] forState:UIControlStateNormal];
lbl_Press.hidden = FALSE;
lbl_updateTime.hidden = TRUE;
flag_for_mic_button = 0;
}
}
-(void)startRecording
{
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
NSError *err = nil;
UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
AudioSessionSetProperty(kAudioSessionProperty_OverrideAudioRoute, sizeof(audioRouteOverride), &audioRouteOverride);
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 numberWithInt:44100.0f] 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];
NSDate *now = [NSDate dateWithTimeIntervalSinceNow:0];
caldate =[now description];
recorderFilePath = [NSString stringWithFormat:#"%#/%# MyRecording.caf",DOCUMENTS_FOLDER,caldate];
NSURL *url = [NSURL fileURLWithPath:recorderFilePath];
err=nil;
audioRecorder = [[AVAudioRecorder alloc]initWithURL:url settings:recordSetting error:&err];
[audioRecorder setDelegate:self];
[audioRecorder prepareToRecord];
audioRecorder.meteringEnabled = YES;
[audioRecorder record];
[self setTimer];
[self hidePlaybackView];
}
-(void)stopRecording
{
[audioRecorder stop];
[start_Timer invalidate];
[self showPlaybackView];
}
-(void)playSound
{
// [self playBackTimer];
if (!recorderFilePath)
{
recorderFilePath = [NSString stringWithFormat:#"%#/%# MyRecording.caf",DOCUMENTS_FOLDER,caldate];
}
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((CFURLRef)CFBridgingRetain(filePath), &soundID);
//Use audio services to play the sound
AudioServicesPlaySystemSound(soundID);
audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:filePath error:nil];
[audioPlayer play];
audioPlayer.delegate = self;
}
EDIT:
-(void)showPlaybackView
{
view_playback = [[UIView alloc]initWithFrame:CGRectMake(0, 600, 320, 80)];
view_playback.backgroundColor = [UIColor grayColor];
[self.view addSubview:view_playback];
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.4];
[UIView setAnimationCurve: UIViewAnimationCurveEaseInOut];
view_playback.frame = CGRectMake(0, 325, 320, 55);
[UIView commitAnimations];
btn_Playback = [UIButton buttonWithType:UIButtonTypeCustom];
[btn_Playback setImage:[UIImage imageNamed:#"play.png"] forState:UIControlStateNormal];
btn_Playback.frame = CGRectMake(10, 10, 35, 35);
[view_playback addSubview:btn_Playback];
[btn_Playback addTarget:self action:#selector(playSound) forControlEvents:UIControlEventTouchUpInside];
btn_done = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[btn_done setTitle:#"Done" forState:UIControlStateNormal];
btn_done.frame = CGRectMake(265, 15, 45, 30);
btn_done.titleLabel.font = [UIFont systemFontOfSize:14.0f];
[view_playback addSubview:btn_done];
[view_playback addSubview:playback_slider];
[btn_done addTarget:self action:#selector(Done) forControlEvents:UIControlEventTouchUpInside];
}
Any help would be appreciable.
Thanks

Try this approach :
-(void)showStopbutton
{
if (![audioPlayer isPlaying])
{
[audioPlayer start];
// other stuff
}
if ([audioPlayer isPlaying])
{
[audioPlayer stop];
// Delete the previous recording in the delegate method of audio player
}
}

I stopped the Audio Player and do not let it resume back by using the following code.
if([audioPlayer isPlaying])
{
audioPlayer.currentTime=0;
}
Happy Coding!

Related

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 do recording for main view?

There is recoding in my app.
I have created a custom ScreenCapture View to do recoding.
Now i want to record a video for main view. (i.e on self.view),but it is not working.
I have used following code to do recording of my custom view :
- (IBAction)btnRecording_Pressed:(id)sender {
if (Isrecording ==YES)
{
//
// imgDustbin.hidden=YES;
// [[NSUserDefaults standardUserDefaults ] setValue:#"NO" forKey:#"DUSTBIN"];
//---
[voiceRecorder stop];
[captureview stopRecording];
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];
// NSString *recorderFilePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];//26
NSString *recorderFilePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
recorderFilePath = [recorderFilePath stringByAppendingPathComponent:#"tempRecording.caf"];
NSURL *urls = [NSURL fileURLWithPath:recorderFilePath];
err = nil;
voiceRecorder = [[ AVAudioRecorder alloc] initWithURL:urls settings:recordSetting error:&err];
//[recorder setMeteringEnabled:YES];
if(!voiceRecorder){
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
[voiceRecorder setDelegate:self];
[voiceRecorder prepareToRecord];
//scrren short of screen
if ([[UIScreen mainScreen] respondsToSelector:#selector(scale)])
UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, NO, [UIScreen mainScreen].scale);
else
UIGraphicsBeginImageContext(self.view.bounds.size);
[captureview.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData * imageData = UIImageJPEGRepresentation(viewImage, 1.0);
// NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);//26
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
documentsDirectory = [documentsDirectory stringByAppendingPathComponent:#"VideoScreen.jpg"];
[imageData writeToFile:documentsDirectory atomically:YES];
//--------------------
[voiceRecorder record];
[captureview performSelector:#selector(startRecording) withObject:nil afterDelay:0];
Isrecording =NO;
[btnRecord setTitle:#"Stop" forState:UIControlStateNormal];
}
else if (!Isrecording)
{
//
imgDustbin.hidden =NO;
[[NSUserDefaults standardUserDefaults ] setValue:#"YES" forKey:#"DUSTBIN"];
//------
[voiceRecorder stop];
[captureview stopRecording];
[self createVideo];
Isrecording=YES;
[btnRecord setTitle:#"Record" forState:UIControlStateNormal];
}
}
how to do this ?
Thanks..
I've removed some project specific code for my setup, but if you have your input and outputs setup the previewing/preview layer code is what you are looking for. You add a sublayer that shows what video will be recorded.
- (void)setupSession{
// create a capture session set session preset
// get a camera, front facing if possible
// check to see if camera is available
// create input
// create output
// add output
[session beginConfiguration];
[session addInput:input];
[session addOutput:output];
[session commitConfiguration];
// configure orientation
connection = [output connectionWithMediaType:AVMediaTypeVideo];
//check to make sure you can record
// Important for you, the preview layer
// add preview layer
captureVideoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:session];
if ([captureVideoPreviewLayer isOrientationSupported])
{
[captureVideoPreviewLayer setOrientation:[[UIDevice currentDevice] orientation]];
} else {
NSLog(#"Cannot set preview orientation");
}
[captureVideoPreviewLayer setFrame:[_previewView bounds]];
//add sublayer to mainview where you are setting your recording from
[[self.view layer] addSublayer:captureVideoPreviewLayer];
// start session
[session startRunning];
}

UISwitch with AVAudioPlayer

Have problem in playsound section.When i turn switch off - soundchecker change his value to NO,but audioplayer not stopping.What's wrong guys?
-(IBAction)Settings {
if(settingsview==nil) {
settingsview=[[UIView alloc] initWithFrame:CGRectMake(10, 130, 300, 80)];
[settingsview setBackgroundColor:[UIColor clearColor]];
UILabel *labelforSound = [[UILabel alloc]initWithFrame:CGRectMake(15, 25, 70, 20)];
[labelforSound setFont:[UIFont systemFontOfSize:18]];
[labelforSound setBackgroundColor:[UIColor clearColor]];
[labelforSound setText:#"Sound"];
SoundSwitch = [[UISwitch alloc]initWithFrame:CGRectMake(10, 50, 20, 20)];
SoundSwitch.userInteractionEnabled = YES;
if(soundchecker == YES) [SoundSwitch setOn:YES];
else [SoundSwitch setOn:NO];
[SoundSwitch addTarget:self action:#selector(playsound:) forControlEvents:UIControlEventValueChanged];
[settingsview addSubview:labelforSound];
[settingsview addSubview:SoundSwitch];
[self.view addSubview:settingsview];
}
else {
[settingsview removeFromSuperview];
[settingsview release];
settingsview=nil;
}
}
//-------Playsound------------------//
-(void)playsound:(id) sender {
NSString *pathtosong = [[NSBundle mainBundle]pathForResource:#"Teachme" ofType:#"mp3"];
AVAudioPlayer* audioplayer = [[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:pathtosong] error:NULL];
if(SoundSwitch.on) {
[audioplayer play];
soundchecker = YES;
}
if(!SoundSwitch.on) {
[audioplayer stop];
soundchecker = NO;
}
}
It's not stopping because every time that playsound is called you are creating a NEW AVAudioPlayer. So when you call [audioplayer stop], you are not calling it on the AVAudioPlayer that is currently playing, you are calling it on a new one you just created.
You could add the AVAudioPlayer variable to the header of your class (as a property if you want). Then you could do this:
-(void)playsound:(id) sender
{
if(SoundSwitch.on)
{
if(!audioPlayer) {
NSString *pathtosong = [[NSBundle mainBundle]pathForResource:#"Teachme" ofType:#"mp3"];
audioplayer = [[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:pathtosong] error:nil];
}
[audioplayer play];
soundchecker = YES;
} else {
if(audioPlayer && audioPlayer.isPlaying) {
[audioplayer stop];
}
soundchecker = NO;
}
}

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 */
}