(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而不使用物理存储?
1条答案
按热度按时间68bkxrlz1#
代码应该很简单,不需要任何字节交换。请参见以下内容:https://docs.unity.cn/540/Documentation/ScriptReference/WWW.GetAudioClip.html