how to record voice and play in iphone - 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 :)

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.

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];
}

Objective C: auto play after recording with specific time

Good day, can you help me with my project in making a recording project, which is after you recorded it using AVAudioRecorder it will automatically play in a certain time can you give me or site me a link regarding with my question..i am badly needed your help masters, because i'm new at iOS development. thanks in advance guys. have a good day.
here's my code # startrecording:
-(void)startRecording:(UIButton *)sender
{ //for recording
recStopBtn.enabled=NO;
recStopBtn.hidden = NO;
recStopBtn.enabled =YES;
playRecBtn.enabled = NO;
loading.hidden = NO;
[loading startAnimating];
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];
// 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:16000.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];
// These settings are used if we are using kAudioFormatLinearPCM format
//[recordSetting setValue :[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];
//[recordSetting setValue :[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsBigEndianKey];
//[recordSetting setValue :[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsFloatKey];
recorderFilePath = [NSString stringWithFormat:#"%#/MySound.caf", DOCUMENTS_FOLDER];
NSLog(#"recorderFilePath: %#",recorderFilePath);
NSURL *url = [NSURL fileURLWithPath:recorderFilePath];
err = nil;
NSData *audioData = [NSData dataWithContentsOfFile:[url path] options: 0 error:&err];
if(audioData)
{
NSFileManager *fm = [NSFileManager defaultManager];
[fm removeItemAtPath:[url path] error:&err];
}
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 record];
lblStatusMsg.text = #"Recording...";
NSLog(#"RECORDING");
//recIcon.image = [UIImage imageNamed:#"rec_icon.png"];
//progressView.progress = 0.0;
//timer = [NSTimer scheduledTimerWithTimeInterval:6.0 target:self selector:#selector(handleTimer) userInfo:nil repeats:YES];
}
If all you need is how to make something happen after a certain amount of time, use an NSTimer. I see you already have one commented out in your code.
To record for a certain amount of time use recordForDuration. To stop recording manually use stop. To play a recording use the url property of the AVAudioRecorder in AVAudioPlayer method initWithContentsOfURL.
So basically, uncomment your NSTimer and then do
AVAudioPlayer *player;
- (void) handleTimer
{
player = [[AVAudioPlayer alloc] initWithContentsOfURL:nameOfAudioRecorder.url];
}

How can i record a song play from iPod library using MPMediaPickerController?

I am making an App in which i have to play music from iPod Music Library using MPMediaPickerController.After playing a song i want to record the song with some external Voice(For example:- User's Voice).I m trying to do the same but getting a problem i.e.when App launches firstly,i choose a song from iPod Music library after that i click on start Recording Button.when i click on Start Recording button my song which i played before stops but the recording is working properly.Recording of User's Voice is working fine but song is not getting recorded as i told that song stops when "Start Recording" button clicked.I am using AVAudioRecorder for Recording.This is my code which i m using.
-(Void)ViewDidLoad
{
self.musicPlayer = [MPMusicPlayerController iPodMusicPlayer];
}
- (void)playOrPauseMusic:(id)sender {
MPMusicPlaybackState playbackState = self.musicPlayer.playbackState;
if (playbackState == MPMusicPlaybackStateStopped || playbackState == MPMusicPlaybackStatePaused) {
[self.musicPlayer play];
} else if (playbackState == MPMusicPlaybackStatePlaying) {
[self.musicPlayer pause];
}
}
- (void)openMediaPicker:(id)sender {
MPMediaPickerController *mediaPicker = [[MPMediaPickerController alloc] initWithMediaTypes:MPMediaTypeMusic];
mediaPicker.delegate = self;
mediaPicker.allowsPickingMultipleItems = NO; // this is the default
[mediaPicker shouldAutorotateToInterfaceOrientation:UIInterfaceOrientationLandscapeRight];
[self presentModalViewController:mediaPicker animated:YES];
}
- (void) startRecording
{
[self.musicPlayer play];
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];
// 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];
recorderFilePath = [NSString stringWithFormat:#"%#/MySound.caf", DOCUMENTS_FOLDER] ;
NSLog(#"recorderFilePath: %#",recorderFilePath);
NSURL *url = [NSURL fileURLWithPath:recorderFilePath];
err = nil;
NSData *audioData = [NSData dataWithContentsOfFile:[url path] options: 0 error:&err];
if(audioData)
{
NSFileManager *fm = [NSFileManager defaultManager];
[fm removeItemAtPath:[url path] error:&err];
}
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) 2];
lblStatusMsg.text = #"Recording...";
selector:#selector(handleTimer) userInfo:nil repeats:YES];
}
This is my Code of MPMusicPlayer and AVAudioRecorder.Please help.Thanks in advance.
You can't record Songs imported from iPod library, you can only record mp3 file, for that you need to convert Mediaitem into mp3 format.
you can get referance for that from here, i hope this may help you.
Maybe look into playing two tracks simultaneously. You could record a separate voice over track and trigger this and your mp3 to start playing at the same time. Obviously this would only work inside your app.