自訂音訊效果

本文說明如何建立一個 Windows 執行階段 元件,實作 IBasicAudioEffect 介面,以建立音訊串流的自訂效果。 你可以用 AudioGraph、 MediaCapture 和 MediaComposition 來使用自訂效果。

Note

IBasicAudioEffect 介面是 Windows.Media.Effects 命名空間中的 Windows 執行階段 API。 這些 API 在 WinUI 3 桌面應用程式中運作方式與 UWP 相同。 主要差別在於你如何設定專案並參考效果元件。

為你的音訊效果新增一個 Windows 執行階段 元件

在 Visual Studio 中,為你的 WinUI 3 解決方案新增一個 Windows 執行階段 元件(C#)專案:

  1. 在 方案總管 中右鍵點擊你的解決方案,選擇新增>Project。
  2. 選擇 Windows 執行階段 元件專案範本。
  3. 專案名稱 為 AudioEffectComponent。
  4. 從你的主 WinUI 3 應用程式中,將專案參考加入這個元件專案。
  5. 將預設類別檔案重新命名為 ExampleAudioEffect.cs。

實作 IBasicAudioEffect 介面

你的音訊效果必須實作 IBasicAudioEffect 介面的所有方法與屬性。

using System.Collections.Generic;
using Windows.Media;
using Windows.Media.Effects;
using Windows.Media.MediaProperties;
using Windows.Foundation.Collections;

namespace AudioEffectComponent;

public sealed class ExampleAudioEffect : IBasicAudioEffect
{
    private AudioEncodingProperties _currentEncodingProperties;
    private IPropertySet _propertySet;
    private float _echoDelay = 0.5f; // delay in seconds
    private float _echoMix = 0.5f;   // mix level (0-1)

    public bool UseInputFrameForOutput => true;

    public IReadOnlyList<AudioEncodingProperties> SupportedEncodingProperties
    {
        get
        {
            var supportedProperties = new List<AudioEncodingProperties>();

            AudioEncodingProperties encodingProps1 =
                AudioEncodingProperties.CreatePcm(44100, 1, 32);
            encodingProps1.Subtype = MediaEncodingSubtypes.Float;
            supportedProperties.Add(encodingProps1);

            AudioEncodingProperties encodingProps2 =
                AudioEncodingProperties.CreatePcm(48000, 1, 32);
            encodingProps2.Subtype = MediaEncodingSubtypes.Float;
            supportedProperties.Add(encodingProps2);

            return supportedProperties;
        }
    }

    public void SetEncodingProperties(
        AudioEncodingProperties encodingProperties)
    {
        _currentEncodingProperties = encodingProperties;
    }

    public void SetProperties(IPropertySet configuration)
    {
        _propertySet = configuration;

        // Read custom properties if provided
        if (configuration != null &&
            configuration.TryGetValue("EchoDelay", out object delay))
        {
            _echoDelay = (float)delay;
        }

        if (configuration != null &&
            configuration.TryGetValue("EchoMix", out object mix))
        {
            _echoMix = (float)mix;
        }
    }

    public void ProcessFrame(ProcessAudioFrameContext context)
    {
        // Audio processing logic goes here.
        // See the echo effect example below.
    }

    public void Close(MediaEffectClosedReason reason)
    {
        // Clean up resources
    }

    public void DiscardQueuedFrames()
    {
        // Discard any cached frames
    }
}

創造回聲效果

以下範例展示了 ProcessFrame 一種產生回聲效果的實作。 此效果會將先前的音訊資料儲存在緩衝區,並在可設定的延遲後與當前音訊資料混合。

要存取原始音訊緩衝區,你需要 IMemoryBufferByteAccess COM 介面。 在你的效果命名空間中加入以下定義:

using System.Runtime.InteropServices;

[ComImport]
[System.Runtime.InteropServices.Guid("5B0D3235-4DBA-4D44-865E-8F1D0E4FD04D")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
unsafe interface IMemoryBufferByteAccess
{
    void GetBuffer(out byte* buffer, out uint capacity);
}

Important

此技術存取原生且未受管理的音訊緩衝區。 你必須在專案<AllowUnsafeBlocks>true</AllowUnsafeBlocks>檔案中新增.csproj內容,才能啟用不安全的程式碼。

private float[] _echoBuffer;
private int _echoBufferPosition;
private float _echoDelay = 0.5f; // delay in seconds
private float _echoMix = 0.5f;   // mix level (0-1)
private Windows.Media.MediaProperties.AudioEncodingProperties _currentEncodingProperties;

public unsafe void ProcessFrame(ProcessAudioFrameContext context)
{
    AudioFrame inputFrame = context.InputFrame;

    using (AudioBuffer inputBuffer =
        inputFrame.LockBuffer(AudioBufferAccessMode.ReadWrite))
    using (IMemoryBufferReference inputReference =
        inputBuffer.CreateReference())
    {
        byte* dataInBytes;
        uint capacityInBytes;

        ((IMemoryBufferByteAccess)inputReference).GetBuffer(
            out dataInBytes, out capacityInBytes);

        float* dataInFloat = (float*)dataInBytes;
        int dataInFloatLength =
            (int)capacityInBytes / sizeof(float);

        // Initialize echo buffer on first call
        if (_echoBuffer == null)
        {
            int delaySamples = (int)(
                _currentEncodingProperties.SampleRate * _echoDelay);
            _echoBuffer = new float[delaySamples];
        }

        for (int i = 0; i < dataInFloatLength; i++)
        {
            float input = dataInFloat[i];
            float echo = _echoBuffer[_echoBufferPosition];

            // Mix the original signal with the echo
            dataInFloat[i] = input + (echo * _echoMix);

            // Store the current sample in the echo buffer
            _echoBuffer[_echoBufferPosition] = input;
            _echoBufferPosition =
                (_echoBufferPosition + 1) % _echoBuffer.Length;
        }
    }
}

將效果新增至音訊圖

要用 AudioGraph 使用自訂效果,請建立一個效果定義的實例,並將其加入節點:

using Windows.Media.Audio;
using Windows.Media.Effects;

var effectDefinition = new AudioEffectDefinition(
    typeof(AudioEffectComponent.ExampleAudioEffect).FullName);

audioFileInputNode.EffectDefinitions.Add(effectDefinition);

將設定傳遞給效果

你可以使用 PropertySet 將設定值傳遞給效果:

var properties = new PropertySet();
properties["EchoDelay"] = 0.3f;
properties["EchoMix"] = 0.6f;

var effectDefinition = new AudioEffectDefinition(
    typeof(AudioEffectComponent.ExampleAudioEffect).FullName,
    properties);

在效果的 SetProperties 方法中(如前所示),從屬性集讀取這些值,以在執行階段設定效果。

將效果加入 MediaCapture

你也可以將自訂音效加入 MediaCapture 音訊串流:

var effectDefinition = new AudioEffectDefinition(
    typeof(AudioEffectComponent.ExampleAudioEffect).FullName);

await _mediaCapture.AddAudioEffectAsync(effectDefinition);