为什么在AVAudioEngine中敲击麦克风时缓冲区中的BytesPerFrame出乎意料地大



我正在尝试从麦克风获取缓冲区数据。

我试图从tap块内的缓冲区值访问BytesPerFrame。我尝试使用 swift 在 xcode 上运行相同的代码,它给出了一个正常的值。只有当我使用 Xamarin.iOS 在 C# 中运行它时,它才会变得奇怪。

我什至尝试使用特定BytesPerFrame = 2 AudioStreamBasicDescription初始化格式,但问题是相同的。

下面是它在 C# 中的样子:

    var engine = new AVAudioEngine();
    var format = new AVAudioFormat(
        format: AVAudioCommonFormat.PCMInt16, 
        sampleRate: 44100, 
        channels: 1, 
        interleaved: false);
    engine.InputNode.InstallTapOnBus(
        bus: 0,
        bufferSize: 4096, 
        format,
        tapBlock: (buffer, when) =>
            {
                Console.WriteLine(buffer.FrameCapacity);
                Console.WriteLine(buffer.Format.StreamDescription.BytesPerFrame);
                // other processing
            });
    engine.StartAndReturnError(out var err);

这是快速版本:

    let format = AVAudioFormat(commonFormat: AVAudioCommonFormat.pcmFormatInt16, sampleRate: Double(44100), channels: 1, interleaved: false)
    engine.inputNode.installTap(onBus: 0, bufferSize: 4096, format: format) { (buffer, time) -> Void in
        let bytesPerFrame = buffer.format.streamDescription.pointee.mBytesPerFrame;
        let frameCapacity = buffer.frameCapacity;
    }
    status = .Recording
    try! engine.start()

在 C# 中,我期望BytesPerFrame值只是 2 但我得到的是像1871587600这样奇怪的巨大东西

这不会在 swift 中发生。

对我来说,

它看起来像Xamarin.iOS中的一个错误。我在他们的GitHub上创建了一个问题:https://github.com/xamarin/xamarin-macios/issues/7890。

对于将来可能到达这里的未来读者来说,重要的问题很可能是以下问题:

我正在尝试从麦克风获取缓冲区数据。

即使描述数据是垃圾,这实际上是可能的。

private void OnBusTap(AVAudioPcmBuffer buffer, AVAudioTime when)
{
    AudioBuffer audioBuffer = buffer.AudioBufferList[0];
    byte[] data = new byte[audioBuffer.DataByteSize];
    Marshal.Copy(audioBuffer.Data, data, 0, audioBuffer.DataByteSize);
    // do something with data. However, note that you are not on the main thread.
}

在我的例子中,OnBusTap每秒调用 10 次,DataByteSize 为 8820,与 44100 的采样率完美匹配。

最新更新