Problem using AVAudioRecorder

瘦欲@ 提交于 2020-01-03 04:28:07

问题


I am facing a strange problem with AVAudioRecorder. In my application i need to record audio and play it. I am creating my player as :

if(recorder)
{
if(recorder.recording)
[recorder stop];
[recorder release];
recorder = nil;
}

NSString * filePath = [NSHomeDirectory() stringByAppendingPathComponent: [NSString stringWithFormat:@"Documents/%@.caf",songTitle]];
        NSDictionary *recordSettings = [[NSDictionary alloc] initWithObjectsAndKeys:
                                        [NSNumber numberWithFloat: 44100.0],AVSampleRateKey,
                                        [NSNumber numberWithInt: kAudioFormatAppleIMA4],AVFormatIDKey,
                                        [NSNumber numberWithInt: 1], AVNumberOfChannelsKey,
                                        [NSNumber numberWithInt: AVAudioQualityMax],AVEncoderAudioQualityKey,nil];
        recorder = [[AVAudioRecorder alloc] initWithURL: [NSURL fileURLWithPath:filePath] settings: recordSettings error: nil];
        recorder.delegate = self;
if ([recorder prepareToRecord] == YES){
                [recorder record];

I am releasing and creating player every time i press record button. But the problem is that ,AVAudiorecorder is taking some time before starting to record , and so if i press record button multiple times continuously ,my application freezes for some time. The same code works fine without any problem when headphones are connected to device...there is no delay in recording, and the app doesn't freeze even if i press record button multiple times.

Will be greatful if anyone guides me in rectifying this issue. Any help in this regard will be highly appreciated.

Thanx in advance.


回答1:


Got the solution. I just added the code

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;
        }
        err = nil;
        [audioSession setActive:YES error:&err];
        if(err){
            NSLog(@"audioSession: %@ %d %@", [err domain], [err code], [[err userInfo] description]);
            return;
        }

and it is now working fine. However i want to know what difference does this piece of code made? And why it was like that my application was working fine with headphones connected but freezed without them.?




回答2:


Yes,

[audioSession setCategory :AVAudioSessionCategoryPlayAndRecord error:&err];

is the solution. It lets you record and play the audio.

About the headphones error, that's probably related with the property

[[AVAudioSession sharedInstance] inputIsAvailable]


来源:https://stackoverflow.com/questions/2800999/problem-using-avaudiorecorder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!