This is similar to this question (kinda outdated), my problem is that I am trying to create an AudioClip from a float array that has been converted from byte array that has been converted from a base64 string. At the end it plays a loud, horrible and fast sound.
You can use this online tool to encode a small .wav file into a base64 string and this other online tool to make sure the large base64 string decoded generates the exact audio file.
I followed the other question solution and also tried changing the frequency value but it still plays a horrible sound. What Am I doing wrong?
AudioSource myAudio;
public float frequency = 44100; //Maybe 22050? since it is a wav mono sound
void Start(){
myAudio = GetComponent<AudioSource>();
}
//When clicking on the game object, play the sound
private void OnMouseDown(){
string audioAsString="UklGRjbPAQBXQVZFZm10IBIAAAABAAEAIlYAAESsAAACABAAAABkYXRh....."; //Base64 string encoded from the online tool. I can't put the whole string here because of max characters warning from StackOverflow questions.
byte[] byteArray = Convert.FromBase64String(audioAsString); //From Base64 string to byte[]
float[] floatArray = ConvertByteArrayToFloatArray(byteArray); //From byte[] to float[]
AudioClip audioClip = AudioClip.Create("test", floatArray.Length , 1, frequency, false);
audioClip.SetData(floatArray, 0);
myAudio.clip = audioClip;
myAudio.Play(); //Plays the audio
}
private float[] ConvertByteArrayToFloatArray(byte[] array)
{
float[] floatArr = new float[array.Length / 4];
for (int i = 0; i < floatArr.Length; i++)
{
if (BitConverter.IsLittleEndian) //I am still not sure what this line does
Array.Reverse(array, i * 4, 4);
floatArr[i] = BitConverter.ToSingle(array, i * 4) / 0x80000000;
}
return floatArr;
}