Need some assistance regarding AVAudioPlayer - ios

This is the code to record and play audio, its creating the audio file perfectly but play code is not playing the file. I cant understand what is going wrong i tried everything nslog, audio file is also generating perfectly in document folder.
- (IBAction)recStartStop:(id)sender
{
if(toggle)
{
[recStartStopBtn setImage:[UIImage imageNamed:#"StopRed"] forState:UIControlStateNormal];
toggle = NO;
playBtn.enabled = toggle;
playBtn.hidden = !toggle;
NSMutableDictionary* recordSetting = [[NSMutableDictionary alloc] init];
[recordSetting setValue :[NSNumber numberWithInt:kAudioFormatAppleIMA4] forKey:AVFormatIDKey];
[recordSetting setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];
[recordSetting 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:recordSetting error:nil];
[recorder setDelegate:self];
[recorder prepareToRecord];
[recorder record];
}
else
{
recStartStopBtn.enabled = NO;
recStartStopBtn.hidden = YES;
playAudioBtn.hidden = NO;
NSLog(#"Using File called: %#",recordedTmpFile);
[recorder stop];
}
}
- (IBAction)playAudio:(id)sender
{
AVAudioPlayer * avPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:recordedTmpFile error:nil];
[avPlayer prepareToPlay];
[avPlayer play];
NSLog(#"%#",recordedTmpFile);
}

Related

Delegates Of AVAudioRecorderDelegate are Not Calling

Actually I want To Record The Audio and Store Into Document, i haveFound FilePath and even attached the audio Files, But i want To attach actual Audio into that Path, It's Not Working, I write that Code in DidFinish like This.
- (void)viewDidLoad {
[super viewDidLoad];
self.navigationItem.title = #"Recording Area";
[btnRecord setBackgroundImage:[UIImage imageNamed:#"Record.png"] forState:UIControlStateNormal];
session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
audioRecorder.delegate = self;
NSDate *today = [[NSDate alloc]init];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"hh:mm:ss"];
NSString *currentTime = [dateFormatter stringFromDate:today];
NSString *outputPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) objectAtIndex:0];
outputPath = [outputPath stringByAppendingString:[NSString stringWithFormat:#"%#.m4a",currentTime]];
NSMutableDictionary *recordDictionary = [[NSMutableDictionary alloc] init];
[recordDictionary setValue:[NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey];
[recordDictionary setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];
[recordDictionary setValue:[NSNumber numberWithInt:2] forKey:AVNumberOfChannelsKey];
audioRecorder = [[AVAudioRecorder alloc]initWithURL:[NSURL fileURLWithPath:outputPath] settings:recordDictionary error:nil];
audioRecorder.meteringEnabled = YES;
[audioRecorder prepareToRecord];
}
and For Recording Audio
-(IBAction)onClickRecord:(id)sender
{
if(player.playing)
{
[player stop];
}
if([[btnRecord backgroundImageForState:UIControlStateNormal]isEqual:[UIImage imageNamed:#"Record.png"]])
{
if (!audioRecorder.recording)
{
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setActive:YES error:nil];
[audioRecorder record];
[btnRecord setBackgroundImage:[UIImage imageNamed:#"Pause.png"] forState:UIControlStateNormal];
}
}
else if([[btnRecord backgroundImageForState:UIControlStateNormal]isEqual:[UIImage imageNamed:#"Pause.png"]])
{
[audioRecorder pause];
[btnRecord setBackgroundImage:[UIImage imageNamed:#"Record.png"] forState:UIControlStateNormal];
}
}
For Saving That Recorded Audio
-(IBAction)onClickSave:(id)sender
{
[audioRecorder stop];
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setActive:NO error:nil];
}
And Finally that Is the Delegates Where My code is Not Working actually i am Not able To call This method
- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag
{
[btnRecord setBackgroundImage:[UIImage imageNamed:#"Record.png"] forState:UIControlStateNormal];
[arrayFiles addObject:recorder.url.absoluteString];
NSLog(#"Array %#",arrayFiles);
}
So Please Specify Me where i am Wrong.
You are setting the delegate before initialising the AVAudioRecorder
Move the
audioRecorder.delegate = self; after init
audioRecorder = [[AVAudioRecorder alloc]initWithURL:[NSURL fileURLWithPath:outputPath] settings:recordDictionary error:nil];
audioRecorder.meteringEnabled = YES;
audioRecorder.delegate = self;
[audioRecorder prepareToRecord];

iPhone - Problems Saving Audio After Recording

I a button that records audio when isNotRecording is false and plays audio when isNotRecording is true. Here is my code in the viewDidLoad function:
NSArray *pathComponents = [NSArray arrayWithObjects:
[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject],
#"MyAudioMemo.m4a",
nil];
NSURL *outputFileURL = [NSURL fileURLWithPathComponents:pathComponents];
// Setup audio session
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
// Define the recorder setting
NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc] init];
[recordSetting setValue:[NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey];
[recordSetting setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];
[recordSetting setValue:[NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey];
// Initiate and prepare the recorder
recorder = [[AVAudioRecorder alloc] initWithURL:outputFileURL settings:recordSetting error:NULL];
recorder.delegate = self;
recorder.meteringEnabled = YES;
[recorder prepareToRecord];
Here is my code to play the sound or record:
if (isNotRecording==NO){
if (player.playing) {
[player stop];
}
if (!recorder.recording) {
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setActive:YES error:nil];
// Start recording
[recorder record];
}
}
else{
if (!recorder.recording){
player = [[AVAudioPlayer alloc] initWithContentsOfURL:recorder.url error:nil];
[player setDelegate:self];
[player play];
}
}
And here is my code to stop the playing/recording:
[recorder stop];
[player stop];
Now, everything works almost perfectly (i.e. I can record and play sounds fine). However, there are two issues. The major one is that after I close out the app and try to play the sound, it does not have a sound to play. I want it to play the previous recording. That is my main issue, but it would also be great if I could reduce the lag from when I press the button and the sound plays. Sometimes, if I press the button and release it very fast, no sound plays at all. Any suggestions are greatly appreciated. However, again, the main issue I need fixed is that the recording doesn't save after I close out the app.
I think what's happening is that when you initialize your AVAudioRecorder when the view loads then that will delete any existing file at the target location, irrespective of whether you start recording at that stage. So I think that's how the file is going missing.
Simplest may be just not to call [recorder prepareToRecord]; when you do, as I suspect that's when your recording is getting deleted.
Or you might want to use a temporary file while recording and move it to the final location when you're notified that the recording is finished, in order to avoid that issue. Code is something like:
NSArray *pathComponents = [NSArray arrayWithObjects:
[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject],
#"MyAudioMemoTemp.m4a",
nil];
NSURL *outputFileURL = [NSURL fileURLWithPathComponents:pathComponents];
// Setup audio session
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
// Define the recorder setting
NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc] init];
[recordSetting setValue:[NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey];
[recordSetting setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];
[recordSetting setValue:[NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey];
// Initiate and prepare the recorder
recorder = [[AVAudioRecorder alloc] initWithURL:outputFileURL settings:recordSetting error:NULL];
recorder.delegate = self;
recorder.meteringEnabled = YES;
[recorder prepareToRecord];
if (isNotRecording==NO){
if (player.playing) {
[player stop];
}
if (!recorder.recording) {
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setActive:YES error:nil];
// Start recording
[recorder record];
}
}
else{
if (!recorder.recording){
NSArray *pathComponents = [NSArray arrayWithObjects:
[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject],
#"MyAudioMemo.m4a",
nil];
NSURL *inputFileURL = [NSURL fileURLWithPathComponents:pathComponents];
player = [[AVAudioPlayer alloc] initWithContentsOfURL:inputFileURL error:nil];
[player setDelegate:self];
[player play];
}
}
- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder
                            successfully:(BOOL)flag
{
if (successfully) {
// Copy temp file used during recording to replace that used when playing
//
pathComponents = [NSArray arrayWithObjects:
[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject],
#"MyAudioMemo.m4a",
nil];
NSURL *targetFileURL = [NSURL fileURLWithPathComponents:pathComponents];
NSError *error = nil;
[[NSFileManager defaultManager] removeItemAtURL:targetFileURL error:&error];
error = nil;
[[NSFileManager defaultManager] copyItemAtURL:recorder.url toURL:targetFileURL error:&error];
}
}

playback is very low with avaudio

I have record and playback routines. see code below. The only problem is that the playback on my device is very low. The volume is okay on the simulator and I have the device volume all of the way up. Is there something else I need to set.
Here's the record code:
NSArray *pathComponents = [NSArray arrayWithObjects:
[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject],
#"MyAudioMemo.m4a",
nil];
NSURL *outputFileURL = [NSURL fileURLWithPathComponents:pathComponents];
// Setup audio session
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
// Define the recorder setting
NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc] init];
[recordSetting setValue:[NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey];
[recordSetting setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];
[recordSetting setValue:[NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey];
// Initiate and prepare the recorder
recorder = [[AVAudioRecorder alloc] initWithURL:outputFileURL settings:recordSetting error:NULL];
recorder.delegate = self;
recorder.meteringEnabled = YES;
[recorder prepareToRecord];
[recorder record];
And the playback:
player = [[AVAudioPlayer alloc] initWithContentsOfURL:recorder.url error:nil];
[player setDelegate:self];
player.meteringEnabled = YES;
player.volume = 1.0;
[player play];
Make your speaker default as there is some time problem audio go througg other routes
[session setCategory:AVAudioSessionCategoryPlayAndRecord withOptions:AVAudioSessionCategoryOptionDefaultToSpeaker error:&sessionError];
Try AVAudioSessionCategoryAmbient mode it has high volume when you play your sound
[session setCategory:AVAudioSessionCategoryAmbient error:&setCategoryError];

iOS7 strange issue. Recorder not stopped

i am developing one app in that app i have used the AudioRecorder. my recorder doesent stop when app is close. red status bar shows when my app is background.
used this code...
NSArray *pathComponents = [NSArray arrayWithObjects:
[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject],
#"MyAudioMemo.m4a",
nil];
NSURL *outputFileURL = [NSURL fileURLWithPathComponents:pathComponents];
// Setup audio session
AVAudioSession *session = [AVAudioSession sharedInstance];
//[session setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
[session setCategory:AVAudioSessionCategoryRecord error:nil];
// Define the recorder setting
NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc] init];
[recordSetting setValue:[NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey];
[recordSetting setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];
[recordSetting setValue:[NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey];
// Initiate and prepare the recorder
delegate.recorder = [[AVAudioRecorder alloc] initWithURL:outputFileURL settings:recordSetting error:nil];
delegate.recorder.delegate=self;
delegate.recorder.meteringEnabled = YES;
[delegate.recorder prepareToRecord];
//[recorder record]; // Do not start recording here
[delegate.recorder updateMeters];
level = [delegate.recorder peakPowerForChannel:0];
//AVAudioSession *audioSession = [AVAudioSession sharedInstance];
//[audioSession setActive:NO error:nil];
timer = [NSTimer scheduledTimerWithTimeInterval:0.2 target:self
selector:#selector(updateAudioMeter)
userInfo:nil
repeats:YES];
-(void)updateAudioMeter
{
AppDelegate * delegate=(AppDelegate *)[[UIApplication sharedApplication]delegate];
[delegate.recorder updateMeters];
level = [delegate.recorder averagePowerForChannel:0];
NSLog(#"%f",level);
if(level<=-120)
{
[delegate.recorder record];
}
else
{
[delegate.recorder stop];
}
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{
[recorder stop];
}
but when my app is close the red status bar shows means my iPhone5 not stop the recording. where may i wrong please help me solve this.

Recorder delegate method not called

NSArray *pathComponents = [NSArray arrayWithObjects:
[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject],
#"MyAudioMemo.m4a",
nil];
NSURL *outputFileURL = [NSURL fileURLWithPathComponents:pathComponents];
// Setup audio session
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
// Define the recorder setting
NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc] init];
[recordSetting setValue:[NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey];
[recordSetting setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];
[recordSetting setValue:[NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey];
// Initiate and prepare the recorder
recorder = [[AVAudioRecorder alloc] initWithURL:outputFileURL settings:recordSetting error:NULL];
recorder.delegate = self;
recorder.meteringEnabled = YES;
[recorder prepareToRecord];
[recorder prepareToRecord];
recorder.meteringEnabled = YES;
//Start the actual Recording
[recorder record];
[recorder updateMeters];
level = [recorder peakPowerForChannel:0];
NSLog(#"%f",level);
i have used this code in viewDidload() method to record a sound sound get in level.
i want to call the deleget method when device get the sound.
-(void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag
{
NSLog(#"Level is %f",level);
}
this method not called.
i am setting recorder delegate in .h file but not called this method why this is happening.
help me to do this.
Thanks in advance.
Are you actually storing the AVAudioRecorder instance somewhere? If you are not then it is likely deallocated by the time the above code finishes.
Try this
-(void)initialiceAudio{
NSArray *pathComponents = [NSArray arrayWithObjects:
[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject],
#"MyAudioMemo.m4a",
nil];
NSURL *outputFileURL = [NSURL fileURLWithPathComponents:pathComponents];
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
// Define the recorder setting
NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc] init];
[recordSetting setValue:[NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey];
[recordSetting setValue:[NSNumber numberWithFloat:5000.0] forKey:AVSampleRateKey];
[recordSetting setValue:[NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey];
// Initiate and prepare the recorder
recorder = [[AVAudioRecorder alloc] initWithURL:outputFileURL settings:recordSetting error:NULL];
recorder.delegate = self;
recorder.meteringEnabled = YES;
[player setVolume: 1.0];
[recorder prepareToRecord];
}
-(IBAction)record:(id)sender {
if (!recorder.recording) {
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setActive:YES error:nil];
recordBtn.selected=YES;
tabBtn.selected = YES;
tabBtn.userInteractionEnabled = NO;
// Start recording
[recorder record];
} else {
}
}
-(void) audioRecorderDidFinishRecording:(AVAudioRecorder *)avrecorder successfully:(BOOL)flag{
recorder = nil;
player = nil;
spinnerView = nil;
UploadAudioViewController *upload = [[UploadAudioViewController alloc]initWithNibName:#"UploadAudioViewController" bundle:nil];
NSLog(#"recorder url----%#",recorderurl);
upload.audioURL = recorderurl;
[self.navigationController pushViewController:upload animated:YES];
}
and make sure - you used AVAudioRecorderDelegate and AVAudioPlayerDelegate

Resources