Unity 中播放 API 获取的音频文件
要在 Unity 中播放获取到的音频文件,你可以使用 Unity 的 AudioSource 组件。以下是一个示例代码,展示了如何在 Unity 中播放音频文件:
using System;
using UnityEngine;
public class AudioPlayer : MonoBehaviour
{
public AudioSource audioSource;
public void PlayAudioClip(AudioClip audioClip)
{
audioSource.clip = audioClip;
audioSource.Play();
}
}
你可以将以上代码添加到你的 Unity 项目中的一个脚本中。然后,在你的 GenshinTextToSpeech 脚本中,将播放音频的代码添加到回调函数中,如下所示:
public class GenshinTextToSpeech : TTS
{
// ...
private AudioPlayer audioPlayer;
private void Awake()
{
m_PostURL = "https://genshinvoice.top/api";
audioPlayer = GetComponent<AudioPlayer>();
}
// ...
private IEnumerator GetVoice(string _msg, Action<AudioClip> _callback)
{
// ...
if (speechRequest.responseCode == 200)
{
AudioClip audioClip = DownloadHandlerAudioClip.GetContent(speechRequest);
_callback(audioClip);
audioPlayer.PlayAudioClip(audioClip);
}
else
{
Debug.LogError("语音合成失败: " + speechRequest.error);
}
// ...
}
// ...
}
在这个示例中,我们添加了一个 AudioPlayer 组件到 GenshinTextToSpeech 脚本所在的游戏对象上。在 GetVoice 函数中,我们调用了 audioPlayer.PlayAudioClip 函数来播放音频文件。
确保你将 AudioSource 组件添加到一个游戏对象上,并将该游戏对象分配给 GenshinTextToSpeech 脚本中的 audioSource 变量。这样,当音频文件下载完成后,就可以使用 audioPlayer 组件来播放音频文件了。
原文地址: https://www.cveoy.top/t/topic/jz4E 著作权归作者所有。请勿转载和采集!