ios - 一起使用 AVCaptureSession 和音频单元会导致 AVAssetWriterInput 出现问题

标签 ios audio core-audio audio-recording

我正在开发一个同时做两件事的 iOS 应用:

  1. 它捕获音频和视频并将它们中继到服务器以提供视频聊天功能。
  2. 它捕获本地音频和视频并将它们编码为 mp4 文件以供后代保存。

不幸的是,当我们使用音频单元配置应用程序以启用回声消除时,录音功能会中断:我们用来编码音频的 AVAssetWriterInput 实例拒绝传入样本。当我们不设置音频单元时,录音工作正常,但回声很糟糕。

为了启用回声消除,我们像这样配置一个音频单元(为简洁起见解释):

AudioComponentDescription desc;
desc.componentType = kAudioUnitType_Output;
desc.componentSubType = kAudioUnitSubType_VoiceProcessingIO;
desc.componentManufacturer = kAudioUnitManufacturer_Apple;
desc.componentFlags = 0;
desc.componentFlagsMask = 0;
AudioComponent comp = AudioComponentFindNext(NULL, &desc);
OSStatus status = AudioComponentInstanceNew(comp, &_audioUnit);
status = AudioUnitInitialize(_audioUnit);

这对于视频聊天来说效果很好,但它破坏了录音功能,录音功能是这样设置的(再次解释——实际的实现分散在几个方法中)。

_captureSession = [[AVCaptureSession alloc] init];

// Need to use the existing audio session & configuration to ensure we get echo cancellation
_captureSession.usesApplicationAudioSession = YES;
_captureSession.automaticallyConfiguresApplicationAudioSession = NO;

[_captureSession beginConfiguration];
AVCaptureDeviceInput *audioInput = [[AVCaptureDeviceInput alloc] initWithDevice:[self audioCaptureDevice] error:NULL];
[_captureSession addInput:audioInput];
_audioDataOutput = [[AVCaptureAudioDataOutput alloc] init];
[_audioDataOutput setSampleBufferDelegate:self queue:_cameraProcessingQueue];
[_captureSession addOutput:_audioDataOutput];
[_captureSession commitConfiguration];

captureOutput 的相关部分看起来像这样:

NSLog(@"Audio format, channels: %d, sample rate: %f, format id: %d, bits per channel: %d", basicFormat->mChannelsPerFrame, basicFormat->mSampleRate, basicFormat->mFormatID, basicFormat->mBitsPerChannel);
if (_assetWriter.status == AVAssetWriterStatusWriting) {
    if (_audioEncoder.readyForMoreMediaData) {
        if (![_audioEncoder appendSampleBuffer:sampleBuffer]) {
            NSLog(@"Audio encoder couldn't append sample buffer");
        }
    }
}

调用 appendSampleBuffer 失败了,但是——这是奇怪的部分——只有当我没有将耳机插入我的手机时。检查发生这种情况时产生的日志,我发现在没有连接耳机的情况下,日志消息中报告的 channel 数为3,而有耳机时, channel 数为1.这解释了编码操作失败的原因,因为编码器被配置为只需要一个 channel 。

我不明白的是为什么我在这里得到三个 channel 。如果我注释掉初始化音频单元的代码,我只能得到一个 channel 并且录音工作正常,但回声消除不起作用。此外,如果我删除这些行

// Need to use the existing audio session & configuration to ensure we get echo cancellation
_captureSession.usesApplicationAudioSession = YES;
_captureSession.automaticallyConfiguresApplicationAudioSession = NO;

录音有效(无论有无耳机,我只能得到一个 channel ),但同样,我们失去了回声消除。

所以,我的问题的症结在于:当我配置一个音频单元以提供回声消除时,为什么我会得到三个音频 channel ?此外,是否有任何方法可以防止这种情况发生或使用 AVCaptureSession 解决此问题?

我考虑过将麦克风音频直接从低级音频单元回调传输到编码器以及聊天管道,但似乎需要必要的 Core Media 缓冲区才能做到这一点如果可能,我想避免的工作。

请注意,聊天和录音功能是由不同的人编写的——他们都不是我——这就是这段代码没有更加集成的原因。如果可能的话,我想避免重构整个困惑局面。

最佳答案

最终,我通过 I/O 音频单元从麦克风收集音频样本,将这些样本重新打包到 CMSampleBuffer,并传递新构建的 来解决这个问题CMSampleBuffer 进入编码器。

进行转换的代码如下所示(为简洁起见进行了缩写)。

// Create a CMSampleBufferRef from the list of samples, which we'll own
AudioStreamBasicDescription monoStreamFormat;
memset(&monoStreamFormat, 0, sizeof(monoStreamFormat));
monoStreamFormat.mSampleRate = 48000;
monoStreamFormat.mFormatID = kAudioFormatLinearPCM;
monoStreamFormat.mFormatFlags = kAudioFormatFlagIsSignedInteger | kAudioFormatFlagsNativeEndian | kAudioFormatFlagIsPacked | kAudioFormatFlagIsNonInterleaved;
monoStreamFormat.mBytesPerPacket = 2;
monoStreamFormat.mFramesPerPacket = 1;
monoStreamFormat.mBytesPerFrame = 2;
monoStreamFormat.mChannelsPerFrame = 1;
monoStreamFormat.mBitsPerChannel = 16;

CMFormatDescriptionRef format = NULL;
OSStatus status = CMAudioFormatDescriptionCreate(kCFAllocatorDefault, &monoStreamFormat, 0, NULL, 0, NULL, NULL, &format);

// Convert the AudioTimestamp to a CMTime and create a CMTimingInfo for this set of samples
uint64_t timeNS = (uint64_t)(hostTime * _hostTimeToNSFactor);
CMTime presentationTime = CMTimeMake(timeNS, 1000000000);
CMSampleTimingInfo timing = { CMTimeMake(1, 48000), presentationTime, kCMTimeInvalid };

CMSampleBufferRef sampleBuffer = NULL;
status = CMSampleBufferCreate(kCFAllocatorDefault, NULL, false, NULL, NULL, format, numSamples, 1, &timing, 0, NULL, &sampleBuffer);

// add the samples to the buffer
status = CMSampleBufferSetDataBufferFromAudioBufferList(sampleBuffer,
                                                        kCFAllocatorDefault,
                                                        kCFAllocatorDefault,
                                                        0,
                                                        samples);

// Pass the buffer into the encoder...

请注意,我已经删除了分配对象的错误处理和清理。

关于ios - 一起使用 AVCaptureSession 和音频单元会导致 AVAssetWriterInput 出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31283122/

相关文章:

audio - 将16Bit PCM值转换为-1到1的值

ios - 验证错误 : Invalid Bundle. ... 中的包包含不允许的文件 'Frameworks'

ios - RightBarButtonItem 未显示在正确的位置

iphone - 如何知道controller是在presentModalViewController中还是在pushViewController中?

ios - 插入蓝牙耳机时 AVAudioEngine 使用错误的格式

ios - 适用于 iOS 的波表合成器

ios - 以编程方式锁定 iPhone 和 iPad 屏幕

c# - 如何在 C# 中合成和输出简单的声波?

Swift 3 - 通过 UnsafeMutableRawPointer 通过引用传递结构?

ios - swift AVAudioEngine 崩溃 : player started when in a disconnected state