1、将返回的byte[]数组,转换成float[]数组,然后将通过
audioSource.clip.SetData()方法,将音频数据赋给audiosource,实现语音播放;但这种只有wav很有可以直接用mp3需要第三方库,我没有试过
int SampleRate = 24000;
AudioClip _audioClip = AudioClip.Create("audioClip", SampleRate * 600, 1, SampleRate, false);
byte[] originalData = response;
float[] _clipData = new float[originalData.Length / 2];
for (int i = 0; i < originalData.Length; i += 2)
{
_clipData[i / 2] = (short)((originalData[i + 1] << 8) | originalData[i]) / 32768.0f;
}
_audioClip.SetData(_clipData, 0);
mp3的请参考:https://blog.csdn.net/L877790502/article/details/119042479文章来源:https://www.toymoban.com/news/detail-513215.html
2、将返回的btye[]数组,使用filestream,先保存为mp3文件,然后,再用www类,读取本地文件,获取www,audioclip,在赋给audiosource,进行音频播放。文章来源地址https://www.toymoban.com/news/detail-513215.html
private void ConvertSound(byte[] respone)
{
File.WriteAllBytes(Application.streamingAssetsPath+"/temp.mp3",originalData);
StartCoroutine(Application.streamingAssetsPath+"/temp.mp3");
}
IEnumerator GetAudioClip(string fullPath)
{
fullPath = "file://" + fullPath;
using (var uwr = UnityWebRequestMultimedia.GetAudioClip(fullPath, AudioType.MPEG))
{
((DownloadHandlerAudioClip)uwr.downloadHandler).streamAudio = true;
yield return uwr.SendWebRequest();
if (uwr.isNetworkError || uwr.isHttpError)
{
debugSongPath2.text = uwr.error;
yield break;
}
DownloadHandlerAudioClip dlHandler = (DownloadHandlerAudioClip)uwr.downloadHandler;
if (dlHandler.isDone)
{
audio.clip = dlHandler.audioClip;
if (audio.clip != null)
{
audio.clip = DownloadHandlerAudioClip.GetContent(uwr);
Debug.Log("Playing song using Audio Source!");
}
else
{
Debug.Log("Couldn't find a valid AudioClip.");
}
}
else
{
Debug.Log("The download process is not completely finished.");
}
}
}
到了这里,关于[unity] 音频的二进制流转化为audioclip的两种方式的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!