Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create AudioClip from byte[]

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 :( .

like image 515
Igor Avatar asked Apr 18 '13 08:04

Igor


1 Answers

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

floatArr[i] = BitConverter.ToSingle(array, i*4) / 0x80000000;
like image 67
jaket Avatar answered Nov 02 '22 12:11

jaket