How to make stable to Record or play sound in ios 7 from ios 6 or later?

  •  For recording a sound you have to add below code before the AVAudioRecorder is being alloc.

 

EX.

NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(

NSDocumentDirectory, NSUserDomainMask, YES);

NSString *docsDir = [dirPaths objectAtIndex:0];

NSString *soundFilePath = [docsDir

stringByAppendingPathComponent:@”tempsound.caf”];

NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];

NSDictionary *recordSettings = [NSDictionary dictionaryWithObjectsAndKeys:

[NSNumber numberWithInt:AVAudioQualityMin],

AVEncoderAudioQualityKey,[NSNumber numberWithInt:16],

AVEncoderBitRateKey,[NSNumber numberWithInt: 2],

AVNumberOfChannelsKey,[NSNumber numberWithFloat:44100.0],

AVSampleRateKey,nil];

NSError *error = nil;

——————Must add for IOS 7———————–

 

AVAudioSession *audioSession = [AVAudioSession sharedInstance];

[audioSession setActive:YES error:nil];

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryRecord error:nil];

 

audioRecorder = [[AVAudioRecorder alloc]

initWithURL:soundFileURL

settings:recordSettings

error:&error];

 

audioRecorder.delegate = self;

 

if (error)

{

NSLog(@”error: %@”, [error localizedDescription]);

} else {

[audioRecorder prepareToRecord];

}

[audioRecorder record];

 

  •  For playing a sound file you have to insert below code before      AVAudioPlayer is being allocated..

 

EX.

 

NSError *error;

 

——————Must add for IOS 7———————–

 

AVAudioSession *audioSession = [AVAudioSession sharedInstance];

[audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];

[audioSession setActive:YES error:nil];

 

audioPlayer = [[AVAudioPlayer alloc]

initWithContentsOfURL:audioRecorder.url

error:&error];

audioPlayer.delegate = self;

if (error)

NSLog(@”Error: %@”,

[error localizedDescription]);

else

[audioPlayer play];

 

 

 

 

  •  Now ,import 1 method for Audio Recording delegate.

 

-(void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully: (BOOL)flag

{

NSLog(@”stoped”);

if (!stoped) {

//NSData *data = [NSData dataWithContentsOfURL:recorder.url];

[recorder record];

NSLog(@”stoped sent and restarted”);

}

}