unity3d 如何在Unity中将base64 mpeg转换为AudioClip?(第2部分)

xqk2d5yq  于 2023-02-13  发布在  其他
关注(0)|答案(1)|浏览(295)

(continuing to the question here... )
经过一番研究,我得到了以下几点:

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);

但是,我听到的只是一些随机的噪音。
Someone suggested converting it to a file first:

[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);
}

然而,为了在Android设备上运行,我需要请求Android权限,这可能会阻止玩家尝试我的游戏。这也会产生很多复杂性,因为我需要处理玩家已经拒绝过一次的情况,这样请求对话框就不会再次出现。
如何正确地将base64 mp3字符串转换为AudioClip而不使用物理存储?

68bkxrlz

68bkxrlz1#

代码应该很简单,不需要任何字节交换。请参见以下内容:https://docs.unity.cn/540/Documentation/ScriptReference/WWW.GetAudioClip.html

byte[] bytes = System.Convert.FromBase64String(data);
            MemoryStream ms = new MemoryStream(bytes);
            ms.Position = 0;
            AudioClip GetAudioClip(bool threeD, bool stream, AudioType.MPEG);

相关问题