Play raw pcm audio

Hello,

I’m trying to load a pcm audio file into an AudioClip that I play then with AudioSource.

The pcm file can be played in the terminal with format s16le, 2 channels and 44100Hz sample rate.

I’m using the following code:

void LoadClip()
    {
        byte[] receivedBytes = File.ReadAllBytes("Assets/Resources/audio.pcm");
        List<float> f_decoding = new List<float>();

        for (int i = 0; i < receivedBytes.Length; i += 2)
        {
            f_decoding.Add(BitConverter.ToInt16(receivedBytes, i));
        }
       
       
        int channels = 2;
        int sampleRate = 44100;
        clip = AudioClip.Create("ClipName", f_decoding.Count, channels, sampleRate, false);
        clip.SetData(f_decoding.ToArray(), 0);

        audioSource.clip = clip;
        audioSource.Play();
    }

Basically I get the byte[ ] from the file and then I convert each pair of bytes into a s16 that is then added to a float list. This float list is then passed to the AudioClip data.

However, when playing the script, the audio is very loud and there is some underlying noise. Is there something obvious I’m overlooking in the procedure?

Cheers

I notice that is I use an AudioMixer with an Attenuation effect and I set the attenuation fader down to -79 it sounds much better. Is there some preprocessing I need to do to the float[ ] before making the Audio Clip?

is the data range -1.0f to 1.0f?

Aha! Yeah, that was it. I was not normalizing. Thanks!