Convert AudioClip to Byte[]

Hi, i need to convert an audioclip to a byte array, i know GetData from audioclip doesn’t help because i tied writing a wav file with it and it can’t be reproduced. Someone who can help me?

GetData is the way to get audio data from an AudioClip. That doesn’t mean you can just dump that data into a .wav file and expect it to be playable. I’m not sure how WAV files work but there’s probably more to it than that.

I found some code online that might help if you’re wanting to write a WAV file: Unity3D: script to save an AudioClip as a .wav file. · GitHub

In fact, i have used that, it creates the wav file first and the write more data over it, it’s good but i need to have the bytes for sending to a server, this server must be able to read it. What i am doing now is using that code you send me, but after create the file, i make unity read all bytes of that file and then upload to the server, something weird :frowning:

I needed a straight forward solution for converting audio clip to byte array :

  public static byte[] Convert(AudioClip clip)
    {
        var samples = new float[clip.samples];
        clip.GetData(samples, 0);

        MemoryStream stream = new MemoryStream();
        BinaryWriter writer = new BinaryWriter(stream);

        int length = samples.Length;
        writer.Write(length);

        foreach (var sample in samples)
        {
            writer.Write(sample);
        }

        return stream.ToArray();
    }
1 Like

I am having difficulty converting audio clip to a byte array (using darklord’s solution). It seems that the float array is populated by NULL after I use GetData and I have no idea why.

Also, why are you writing the value of the float array length into the memory stream?

float can not be NULL … and GetData doesn’t reassign the samples variable … the issue seems to be somewhere else

And you prepend the length of the array so that on receiver side you can recreate the array again by

  • first reading 4 bytes → length
  • create new float[length]
  • now copy the rest into the float array with given length