使用AVAudioRecorder进行录制声音,在初始化的时候会卡一下

xlfrank
  • 47

最近在做录音的功能,遇到了一个问题,我使用AVAudioRecorder进行录音,参数包括对象初始化都放在了界面的viewdidload方法里,在进行录音的时候调用 recordForDuration方法, 因为我要限制最长可以录制多长时间,所以就用这个方法对录音文件及参数进行赋值, 因为我界面上有当前音频峰值的显示,所以在开始录音的时候界面效果有些变化,

我现在遇到的难题是:当点击开始录音按钮的时候, 界面效果会等到recordForDuration方法执行完才执行,执行recordForDuration这个方法又需要短暂的停顿,但又不能使用异步去做, 因为界面效果给用户的感觉就是可以录音了,

贴代码

录音工具类:

@implementation SoundUtils

-(SoundUtils *)init
{
self = [super init];
NSError *error = nil;
_recorderFilePath = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent: [NSString stringWithFormat: @"%.0f.%@", [NSDate timeIntervalSinceReferenceDate] * 1000.0, @"caf"]]];
//录音设置
NSMutableDictionary *recordSetting = [[[NSMutableDictionary alloc] init] autorelease]; //录音格式
[recordSetting setValue :[NSNumber numberWithInt:kAudioFormatLinearPCM] forKey: AVFormatIDKey]; //采样率
[recordSetting setValue :[NSNumber numberWithFloat:10000] forKey: AVSampleRateKey];
//通道数
[recordSetting setValue :[NSNumber numberWithInt:1] forKey: AVNumberOfChannelsKey]; //线性采样位数
[recordSetting setValue :[NSNumber numberWithInt:9] forKey: AVLinearPCMBitDepthKey];

_recorder = [[ AVAudioRecorder alloc] initWithURL:_recorderFilePath settings:recordSetting error:&error];
_recorder.delegate = self;
lowPassResults = 0;
return self;
}
-(void) recordM
{
NSError *error = nil;
AVAudioSession * audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error: &error];
[audioSession setActive:YES error: &error];
NSString *duration = [[NSUserDefaults standardUserDefaults] objectForKey:config_durationKey];
int recordDuration = 60;
if(duration == nil){
recordDuration = 60;
}else{
recordDuration = [duration intValue] / 1000;
}
_recorderStartTime = _recorder.currentTime;

AppLog(@"开始计时 %f",[[NSDate date] timeIntervalSince1970]);
_recorder.meteringEnabled = YES;
[_recorder recordForDuration:recordDuration];
AppLog(@"计时结束 %f",[[NSDate date] timeIntervalSince1970]);
}
界面:
- (void)viewDidLoad
{
_soundUtils = [[SoundUtils alloc] init];
}
//开始录音
-(void) recordStart
{
_progressBgImageView.alpha = 1;
if (_timer) {
[_timer invalidate];
_timer = nil;
}
_timer = [NSTimer scheduledTimerWithTimeInterval: 0.001
target: self
selector: @selector(handleTimer:)
userInfo: nil
repeats: YES];
[_soundUtils recordM];

}
- (void) handleTimer: (NSTimer *) timer
{
//峰值动画
}

回复
阅读 6.6k
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
宣传栏