My current approach is to take an AudioClip, turn it into a byte array, then put it into an UploadHandler, attached to a UnityWebRequest, to send a POST request to a server.
Right now, when I pass through an AudioClip to my ConvertAudioToByteArray() function I essentially get back a byte array full of NULL characters. This seems to happen when I use the GetData method on the clip parameter, as a bunch of 0s print out when I Debug.Log the foreach loop of floatArrayOfClip. When I send out a post request to my dev server I get a ProtocolError on the client side.
I believe I have tested everything. The audioClip argument is a microphone recording and is working correctly. Dev server is working correctly. The program is connecting successfully to the dev server.
Using Unity 2021.3.
Thanks in advance.
public void initiateCoroutine(AudioClip audioClip)
{
StartCoroutine(postRequest(audioClip));
}
IEnumerator postRequest(AudioClip audioClip)
{
// convert audio to byte array
byte[] byteArray = ConvertAudioToByteArray(audioClip);
// create UWW and handler, and attach handler to UWW
UnityWebRequest uwr = new UnityWebRequest("-CORRECT URI-", "POST");
UploadHandler uploader = new UploadHandlerRaw(byteArray);
uwr.uploadHandler = uploader;
yield return uwr.SendWebRequest();
if (uwr.result == UnityWebRequest.Result.ConnectionError)
{
Debug.Log(uwr.error);
}
else if (uwr.result == UnityWebRequest.Result.ProtocolError)
{
Debug.Log(uwr.error);
Debug.Log("PROTOCOL");
}
else if (uwr.result == UnityWebRequest.Result.DataProcessingError)
{
Debug.Log(uwr.error);
Debug.Log("PROCESSING");
}
else
{
Debug.Log(uwr.result);
Debug.Log(uwr.downloadHandler.text);
}
}
private static byte[] ConvertAudioToByteArray(AudioClip clip)
{
// get user recording and convert user recording into a float array
var floatArrayOfAudioClip = new float[clip.samples];
clip.GetData(floatArrayOfAudioClip, 0);
// Create buffer stream
MemoryStream stream = new MemoryStream();
BinaryWriter writer = new BinaryWriter(stream);
// Populate audio clip floats into buffer stream
foreach (var sample in floatArrayOfAudioClip)
{
writer.Write(sample);
}
byte[] bytes = stream.ToArray();
return bytes;
}