Home > Software engineering >  How to convert base64 mpeg to AudioClip in Unity?
How to convert base64 mpeg to AudioClip in Unity?

Time:01-16

After some research, I have got the following

private float[] Normalize(float[] data)  {
    float max = float.MinValue;
    for (int i = 0; i < data.Length; i  ){
        if (System.Math.Abs(data[i]) > max) max = System.Math.Abs(data[i]);
    }
    for (int i = 0; i < data.Length; i  ) data[i] = data[i] / max;
    return data;
}

private float[] ConvertByteToFloat(byte[] array){
    float[] floatArr = new float[array.Length / 4];
    for (int i = 0; i < floatArr.Length; i  ){
        if (System.BitConverter.IsLittleEndian)  System.Array.Reverse(array, i * 4, 4);
        floatArr[i] = System.BitConverter.ToSingle(array, i * 4) ;
    }
    return Normalize(floatArr);
}
byte[] bytes = System.Convert.FromBase64String(data);
float[] f = ConvertByteToFloat(bytes);
qa[i] = AudioClip.Create("qjAudio", f.Length, 2, 44100, false);
qa[i].SetData(f,0);

However, all I heard was some random noise.

How can I correctly convert a base64 mp3 string into AudioClip?

CodePudding user response:

I have done some reseach and come up that UnityWebRequestMultimedia.GetAudioClip is way to go.

  1. Convert your base64 string into byte array var audioBytes = Convert.FromBase64String(base64EncodedMp3String);
  2. Create temp path to store it as reference var tempPath = Application.persistentDataPath "tmpMP3Base64.mp3";
  3. Write all bytes to that path File.WriteAllBytes(tempPath, audioBytes);
  4. Use UnityWebRequestMultimedia.GetAudioClip to read from that path UnityWebRequest request = UnityWebRequestMultimedia.GetAudioClip(tempPath, AudioType.MPEG);

Here is a complete example:

[SerializeField] private AudioSource _audioSource;
private void Start()
{
    StartCoroutine(ConvertBase64ToAudioClip(EXAMPLE_BASE64_MP3_STRING, _audioSource));
}
        
IEnumerator ConvertBase64ToAudioClip(string base64EncodedMp3String, AudioSource audioSource)
{
    var audioBytes = Convert.FromBase64String(base64EncodedMp3String);
    var tempPath = Application.persistentDataPath   "tmpMP3Base64.mp3";
    File.WriteAllBytes(tempPath, audioBytes);
    UnityWebRequest request = UnityWebRequestMultimedia.GetAudioClip(tempPath, AudioType.MPEG);
    yield return request.SendWebRequest();
    if (request.result.Equals(UnityWebRequest.Result.ConnectionError))
        Debug.LogError(request.error);
    else
    {
        audioSource.clip = DownloadHandlerAudioClip.GetContent(request);
        audioSource.Play();
    }

    File.Delete(tempPath);
}
  • Related