This commit is contained in:
sin365 2024-08-22 14:40:36 +08:00
parent bfc8651b1e
commit 9a631912f3

View File

@ -14,7 +14,7 @@ public class UniSoundPlayer : MonoBehaviour, ISoundPlayer
void Awake()
{
AudioClip dummy = AudioClip.Create("dummy", 1, 1, AudioSettings.outputSampleRate, false);
AudioClip dummy = AudioClip.Create("dummy", 1, 2, AudioSettings.outputSampleRate, false);
dummy.SetData(new float[] { 1, 1 }, 0);
m_as.clip = dummy;
m_as.loop = true;
@ -62,6 +62,17 @@ public class UniSoundPlayer : MonoBehaviour, ISoundPlayer
var delta = current - lastElapsed;
lastElapsed = current;
audioFPS = 1d / delta.TotalSeconds;
for (int i = 0; i < samples_a; i++)
{
short left = BitConverter.ToInt16(buffer, i * 2 * 2);
//short right = BitConverter.ToInt16(buffer, i * 2 * 2 + 2);
_buffer.Write(left / 32767.0f);
//_buffer.Write(right / 32767.0f);
}
return;
float[] floatdata = ConvertByteArrayToFloatArray(buffer, samples_a, 2);
for (int i = 0; i < samples_a; i++)
{
@ -69,20 +80,23 @@ public class UniSoundPlayer : MonoBehaviour, ISoundPlayer
}
}
public float[] ConvertByteArrayToFloatArray(byte[] bytes, int sampleRate, int channels)
float[] floatArray = new float[960];
public float[] ConvertByteArrayToFloatArray(byte[] buffer, int samples_a, int channels)
{
int sampleCount = bytes.Length / (channels * 2); // 16位所以每个样本2字节
float[] floatArray = new float[sampleCount * channels];
//int sampleCount = buffer.Length / (channels * 2); // 16位所以每个样本2字节
for (int i = 0; i < sampleCount; i++)
for (int i = 0; i < samples_a; i++)
{
// 读取左右声道
short left = BitConverter.ToInt16(bytes, i * channels * 2);
short right = BitConverter.ToInt16(bytes, i * channels * 2 + 2);
//short left = BitConverter.ToInt16(buffer, i * channels * 2);
//short right = BitConverter.ToInt16(buffer, i * channels * 2 + 2);
// 转换为-1.0到1.0的浮点数
floatArray[i] = left / 32767.0f; // 32767是16位整数的最大值
floatArray[i + 1] = right / 32767.0f;
//floatArray[i] = left / 32767.0f; // 32767是16位整数的最大值
//floatArray[i + 1] = right / 32767.0f;
short onedata = BitConverter.ToInt16(buffer, i * channels * 2);
floatArray[i] = onedata / 32767.0f;
}
return floatArray;