【发布时间】:2018-08-08 15:08:27
【问题描述】:
我需要播放声音并能够从缓冲区录制旋律。但我不明白,如何设置AVAudioSession 类别和/或AVAudioPlayerNode 以实现我的目标。 声音安排在播放器节点中。如果我理解正确,AVAudioRecorder 仅从麦克风录制,而不是音乐,与 AVAudioPlayerNode 一起播放。所以,这是我的尝试:
首先我设置一个会话:
NSError *error = nil;
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord
withOptions:AVAudioSessionCategoryOptionMixWithOthers
error:&error];
if (error) {
NSLog(@"AVAudioSession error %ld, %@", error.code, error.localizedDescription);
}
[audioSession setActive:YES error:&error];
if (error) {
NSLog(@"AVAudioSession error %ld, %@", error.code, error.localizedDescription);
}
设置文件进行记录:
NSString* docs = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"Recording.caf"];
NSURL* url = [NSURL fileURLWithPath:docs];
NSError* error = nil;
self.fileForRecording = [[AVAudioFile alloc] initForWriting:url
settings:[self.engine.inputNode inputFormatForBus:0].settings
error:&error];
if (error) {
NSLog(@"CREATE FILE ERROR %@", error);
}
然后,一个引擎:
self.engine = [AVAudioEngine new];
self.player = [AVAudioPlayerNode new];
AVAudioOutputNode *output = self.engine.outputNode;
[self.engine attachNode:self.player];
[self.engine connect:self.player to:output fromBus: 0 toBus: 0 format: format];
[self.engine prepare];
以及记录方法:
- (void)startRecording {
AVAudioFormat* recordingFormat = [self.engine.outputNode outputFormatForBus:0];
if (recordingFormat.sampleRate > 0) {
typeof(self) weakSelf = self;
[self.engine.inputNode installTapOnBus:0
bufferSize:1024
format:recordingFormat
block:^(AVAudioPCMBuffer * _Nonnull buffer, AVAudioTime * _Nonnull when) {
NSError* error;
[weakSelf.fileForRecording writeFromBuffer:buffer error:&error];
NSLog(@"WRITE ERROR %@", error);
}];
}
}
在总线上安装 Tap 时,我尝试使用 nil 作为录音格式,在这种情况下,block 从未调用过。我尝试使用[self.engine.mainMixerNode outputFormatForBus:0];,这会导致崩溃。使用self.engine.outputNode 也会产生崩溃。
请帮忙:)
【问题讨论】:
标签: ios iphone avfoundation avaudioengine