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,我更新了我的代码以反映当前状态。感谢所有回答过我的人提供的帮助。
[self.player prepareToPlay]
? - Bo A