如何使用Xamarin的AudioUnit录制音频。

问题描述 投票:0回答:1

我试图使用AudioUnit来录制音频。

我有下面的代码。但是SetFormat方法返回PropertyNotWritable. 我已经能够使用这样的代码来使用相同的格式参数播放音频。但是不能让它用于录制音频。

(注意Xamarin似乎缺少RemoteIO常量:( )

  const int AudioUnitSubTypeRemoteIO = ('r' << 24) + ('i' << 16) + ('o' << 8) + 'c';
  readonly AudioUnit.AudioUnit _audioUnit;

  public AudioRecorderIos()
  {
     var audioComponentDescription = new AudioComponentDescription()
     {
        ComponentType = AudioComponentType.Output,
        ComponentSubType = AudioUnitSubTypeRemoteIO,
        ComponentManufacturer = AudioComponentManufacturerType.Apple,
        ComponentFlags = 0,
        ComponentFlagsMask = 0
     };

     AudioComponent defaultOutput = AudioComponent.FindNextComponent(null, ref audioComponentDescription);
     _audioUnit = defaultOutput.CreateAudioUnit();

     const int sampleRate = 8000;
     const int channels = 1;
     const int bytesPerSample = 2;
     int framesPerPacket = 1;

     var streamFormat = new AudioStreamBasicDescription()
     {
        SampleRate = sampleRate,
        Format = AudioFormatType.LinearPCM,
        FormatFlags = AudioFormatFlags.LinearPCMIsSignedInteger | AudioFormatFlags.IsPacked,
        ChannelsPerFrame = channels,
        BytesPerFrame = bytesPerSample * channels,
        BitsPerChannel = bytesPerSample * 8,
        BytesPerPacket = framesPerPacket * bytesPerSample * channels,
        FramesPerPacket = framesPerPacket,
        Reserved = 0
     };

     AudioUnitStatus status = _audioUnit.SetFormat(streamFormat, AudioUnitScopeType.Output);
     if (status != AudioUnitStatus.OK)
     {
        throw new ArgumentOutOfRangeException($"Failed to set Audio Format with error {status}");
     }

     _audioUnit.SetRenderCallback(InputCallback, AudioUnitScopeType.Output);

     _audioUnit.Initialize();

更新。 如果我忽略SetFormat的输出,并在初始化后调用GetFormat,那么我得到的格式选项非常不同,如果我随后更新我的格式请求,使之与它选择的格式相同,那么我仍然得到PropertyNotWritable。所以我认为这和我选择的格式值没有关系。我也在网上找到了人们使用和我完全相同的格式选项的例子。

c# .net xamarin.ios audiounit
1个回答
0
投票

我需要调用_audioUnit.SetEnableIO(true, AudioUnitScopeType.Input, 1)来启用录音。以及在Info.plist中添加 "隐私 - 麦克风使用说明"。

并在SetFormat和SetInputCallback方法中设置audioUnitElement参数为1。

© www.soinside.com 2019 - 2024. All rights reserved.