0

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;
} 
Lolpez
  • 849
  • 8
  • 17
  • 3
    If it’s actually a wav file you can’t just convert the bytes into floats and play them. You have to treat it as a wav file – Sami Kuhmonen Jul 13 '21 at 21:18
  • Endianess refers to the order of the bytes of a word. Big endian stores the most significant byte at the smallest memory address. Little endian stores the least significant byte at the smallest memory address. – hijinxbassist Jul 13 '21 at 23:07
  • See wiki for structure of wav : https://en.wikipedia.org/wiki/WAV – jdweng Jul 14 '21 at 03:58
  • Hello @Lolpez did you find a solution to this? – iqra Aug 08 '23 at 16:56

0 Answers0