当我的视图加载时,我通过以下方式设置了一个 AVAudioRecorder 实例:
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
audioSession.delegate = self;
[audioSession setActive:YES error:nil];
[audioSession setCategory:AVAudioSessionCategoryRecord error:nil];
NSString *tempDir = NSTemporaryDirectory();
NSString *soundFilePath = [tempDir stringByAppendingPathComponent:@"sound.m4a"];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
NSLog(@"%@", soundFileURL);
NSDictionary *recordSettings = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:kAudioFormatMPEG4AAC], AVFormatIDKey,
[NSNumber numberWithInt:AVAudioQualityMin], AVEncoderAudioQualityKey,
[NSNumber numberWithInt:16], AVEncoderBitRateKey,
[NSNumber numberWithInt: 1], AVNumberOfChannelsKey,
[NSNumber numberWithFloat:8000.0], AVSampleRateKey,
[NSNumber numberWithInt:8], AVLinearPCMBitDepthKey,
nil];
NSError *error = nil;
self.recorder = [[AVAudioRecorder alloc]
initWithURL:soundFileURL
settings:recordSettings
error:&error];
self.recorder.delegate = self;
if (error) {
NSLog(@"error: %@", [error localizedDescription]);
} else {
[self.recorder prepareToRecord];
}
然后,当用户按下录制按钮时,我会:
- (IBAction)record:(id)sender {
if (!self.isRecording) {
self.isRecording = YES;
[self.recorder record];
self.recordButton.enabled = NO;
}
}
然后停止录制/播放:
- (IBAction)stop:(id)sender {
if (self.isRecording) {
[self.recorder stop];
self.recordButton.enabled = YES;
self.isRecording = NO;
}
if (self.isPlaying) {
[self.player stop];
self.isPlaying = NO;
self.playButton.enabled = YES;
}
}
之后,我希望能够播放录制的内容,所以我执行以下操作:
- (IBAction)play:(id)sender {
NSError *error = nil;
self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:self.recorder.url error:&error];
self.player.delegate = self;
if (error) {
NSLog(@"%@", error.localizedDescription);
} else {
self.isPlaying = YES;
[self.player play];
self.playButton.enabled = NO;
}
}
但是当我去播放文件时得到OSStatus 错误 -43文件未找到。
顺便说一句,这一切都在设备上运行,在模拟器上尝试实例化记录器或播放器时出现错误,从我看来这是一个模拟器问题。
编辑 1:我解决了 OSStatus 错误 -43 部分,它与编码格式有关,我注释掉了格式并正确记录和播放文件,但我需要以压缩格式记录。有谁知道这个的设置?
编辑 2:我设法找到适用于压缩 AAC 音频的设置。一个 2 分钟的音频文件大小为 256KB,我更新了代码以反映当前状态。感谢所有回答您的帮助的人。