unityj將AudioClip數據存儲到字節數組中

做語音聽寫時,需要將錄製的音頻存儲到字節數組中,然後進行語音聽寫功能,但AudioClip只能獲取float[]類型的數據,下面是解決辦法:

 public static byte[] ConvertClipToBytes(AudioClip clip)
        {
            //clip.length;
            float[] samples = new float[clip.samples];

            clip.GetData(samples, 0);

            short[] intData = new short[samples.Length];
            //converting in 2 float[] steps to Int16[], //then Int16[] to Byte[]

            byte[] bytesData = new byte[samples.Length * 2];
            //bytesData array is twice the size of
            //dataSource array because a float converted in Int16 is 2 bytes.

            int rescaleFactor = 32767; //to convert float to Int16

            for (int i = 0; i < samples.Length; i++)
            {
                intData[i] = (short)(samples[i] * rescaleFactor);
                byte[] byteArr = new byte[2];  
                byteArr = BitConverter.GetBytes(intData[i]);
                byteArr.CopyTo(bytesData, i * 2);
            }

            return bytesData;
        }

 

最後的bytesData就是獲取的音頻文件的字節數據。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章