好久没更新博客了,利用这十分钟来写篇服务器语音识别后播放的语音功能
PC端
直接上代码:文章来源:https://www.toymoban.com/news/detail-558379.html
namespace Jeremy {
public class AudioPlayCtrl : MonoBehaviour {
public static AudioPlayCtrl instance { get; private set; }
public AudioSource audioSource { get; set; }
private AudioClip _IntroduceClip;
private void Awake() {
instance = this;
audioSource = transform.GetComponent<AudioSource>();
if (audioSource == null) {
audioSource = transform.gameObject.AddComponent<AudioSource>();
}
}
Coroutine AudioPlay;
public void Play(params string[] urls) {
if (AudioPlay != null)
StopCoroutine(AudioPlay);// StopAllCoroutines();
AudioPlay = StartCoroutine(GetIntroduceAudioClip(audioSource, urls));
}
IEnumerator GetIntroduceAudioClip(AudioSource _aud, params string[] url) {
_aud.Stop();
// MPEG:mp3 OGGVORBIS:ogg WAV:wav
AudioType audioType = AudioType.MPEG;
for (int i = 0; i < url.Length; i++) {
if (url[i] != "") {
var uwr = UnityWebRequestMultimedia.GetAudioClip(url[i], audioType);
yield return uwr.SendWebRequest(); // 完成加载
if (!uwr.isNetworkError && uwr.isDone) {
_IntroduceClip = DownloadHandlerAudioClip.GetContent(uwr);
_aud.clip = _IntroduceClip; // 样本完成
_aud.Play();
if (url.Length > 1 && i < url.Length - 1)
yield return new WaitForSeconds(_aud.clip.length + 0.5f);
}
else
Debug.LogError(uwr.error);
}
}
}
}
}
调用:
效果图:
WebGL文章来源地址https://www.toymoban.com/news/detail-558379.html
语音下载播放做法
Coroutine AudioPlay;
AudioClip downloadedClip;
public AudioSource audioSource { get; set; }
public void Play(params string[] urls) {
StopPlaying();
AudioPlay = StartCoroutine(LoadAudioClips(urls));
}
IEnumerator LoadAudioClips(string[] audioUrls) {
foreach (string url in audioUrls) {
if (url != null && url != "")
using (UnityWebRequest www = UnityWebRequestMultimedia.GetAudioClip(url, AudioType.MPEG)) {
yield return www.SendWebRequest();
if (www.result == UnityWebRequest.Result.ConnectionError ||
www.result == UnityWebRequest.Result.ProtocolError) {
Debug.LogError("Failed to load audio: " + url + ", error: " + www.error);
}
else {
downloadedClip = DownloadHandlerAudioClip.GetContent(www);
audioSource.clip = downloadedClip;
audioSource.Play();
//Debug.Log(url);
while (audioSource.isPlaying) {
yield return null;
}
}
}
}
}
public void StopPlaying() {
if (AudioPlay != null) {
StopCoroutine(AudioPlay);
}
audioSource.Stop();
}
到了这里,关于unity 音频加载并播放的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!