create AudioClip from byte[]

2019-01-24 09:00发布

I have problem. I use sqlite to store sounds. I get sound from it in byte[]. Then convert byte[] to float[]:

            private float[] ConvertByteToFloat(byte[] array) 
            {
                float[] floatArr = new float[array.Length / 4];
                for (int i = 0; i < floatArr.Length; i++) 
                {
                    if (BitConverter.IsLittleEndian) 
                        Array.Reverse(array, i * 4, 4);
                    floatArr[i] = BitConverter.ToSingle(array, i * 4);
                }
                return floatArr;
            } 


            float[] f = ConvertByteToFloat(bytes);

Then create AudioClip:

    AudioClip audioClip = AudioClip.Create("testSound", f.Length, 1, 44100, false, false);
    audioClip.SetData(f, 0);

And then play it

AudioSource.PlayClipAtPoint(audioClip, new Vector3(100, 100, 0), 1.0f);

But result is noise :( .

1条回答
别忘想泡老子
2楼-- · 2019-01-24 09:41

floatArr needs to be scaled to be within the range of -1.0f to 1.0f.

floatArr[i] = BitConverter.ToSingle(array, i*4) / 0x80000000;
查看更多
登录 后发表回答