如何更改下面的代码以使用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)
{
}