Unity AudioClip和PCM音频数据的转化

1 PCM音频数据转化AudioClip

  假设PCM音频当前是16Khz采样率,16bit数据

 byte[] pcmBytes=new byte[10240];
 float[] floatClipData = new float[audioBytes.Length/2];
 for (int i = 0; i < audioBytes.Length; i+=2)
 {  
     floatData[i / 2] = (short)((audioBytes[i + 1] << 8) | audioBytes[i]) / 32768.0f;
 }
 // 构造一个新的AudioClip
 AudioClip audioClip = AudioClip.Create("PCMClip", floatData.Length, 1, 16000, false);
 // 将音频数据设置到AudioClip中
 audioClip.SetData(floatData, 0);
 audiosource.clip = audioClip;
 audiosource.Play();

2 提取AudioClp中的数据转化为PCM bytes字节数组

AudioClip audioClip = new AudioClip();
float[] audioData = new float[audioClip.samples * audioClip.channels];
audioClip.GetData(audioData, 0);
byte[] pcmBytesData = new byte[audioData.Length * 2];
for (int i = 0; i < audioData.Length; i++)
{
    short value = (short)(audioData[i] * short.MaxValue);
    pcmBytesData[i * 2] = (byte)(value & 0x0F);
    pcmBytesData[i * 2 + 1] = (byte)((value >> 8) & 0x0F);
}

你可能感兴趣的:(unity,pcm,音视频)