如何更改下面的代码以使用PCMReaderCallback从Microphone.Start创建的音频剪辑中读取数据?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class NewBehaviourScript : MonoBehaviour
{
    private string m_deviceName = null;
    private AudioClip m_audioClip;

    void Start()
    {
        bool loop = true;
        int lengthSec = 10;
        int frequency = 44100;

        m_audioClip = Microphone.Start(m_deviceName, loop, lengthSec, frequency);
    }

    void Stop()
    {
        Microphone.End(m_deviceName);
        m_audioClip = null;
    }
}

最佳答案

您不能将Microphone API与PCMReaderCallback一起使用。这是因为PCMReaderCallback是通过将PCMReaderCallback函数传递给AudioClip.Create函数而注册的,该函数返回一个新的AudioClip。 Unity的Microphone.Start函数返回AudioClip,但不将PCMReaderCallback作为参数。

如果这不是麦克风,而是简单的音频剪辑,则可以使用以下示例:

public int lengthSamples = 400;
public int channels = 2;
public int frequency = 16000;

AudioSource adSource;

void Start()
{
    adSource = GetComponent<AudioSource>();
    AudioClip clip = AudioClip.Create("clip", lengthSamples, channels, frequency, true, OnAudioRead);
    adSource.clip = clip;
    adSource.Play();
}

//PCMReaderCallback callback
void OnAudioRead(float[] data)
{

}

如果您只想从麦克风读取音频数据,仍然可以使用 OnAudioFilterRead AudioSource.clip.GetData 函数。以下是OnAudioFilterRead的示例。
string m_deviceName = null;
AudioSource adSource;

void Start()
{
    adSource = GetComponent<AudioSource>();
    bool loop = true;
    int lengthSec = 10;
    int frequency = 44100;

    AudioClip clip = Microphone.Start(m_deviceName, loop, lengthSec, frequency);
    adSource.clip = clip;
    while (!(Microphone.GetPosition(null) > 0)) { }

    adSource.Play();
}

void OnAudioFilterRead(float[] data, int channels)
{

}

09-26 09:09