c# - 统一播放多个音频片段
问题描述
可能有与此类似的问题,但我找不到任何有用的问题。
我有一个简单的脚本,其中包含一个类列表,其中包含每个元素的音频剪辑、ID 和事件系统。
我需要将该音频剪辑字段列出并按顺序播放,直到最后一个然后停止并触发事件。
这是我只有一个音频剪辑插槽的代码:(我也尝试了音频剪辑数组,但它只是播放音频剪辑数组上的第一个)
public class MainAudioManager : MonoBehaviour {
public List<soundInfo> currentsoundinfoList = new List<soundInfo>();
AudioSource audioSource;
soundInfo curentSoundInfo;
float audioLenght;
void Start () {
audioSource = gameObject.GetComponent<AudioSource> ();
}
public void SetAudioToPlay (int ID) {
for (int i = 0; i < currentsoundinfoList.Count; i++) {
if (currentsoundinfoList [i].ID == ID) {
curentSoundInfo = currentsoundinfoList[i];
audioSource.clip = curentSoundInfo.clipToPlay;
audioSource.Play ();
audioLenght = audioSource.clip.length;
StartCoroutine ("waitnigTillEbd");
return;
}
}
}
IEnumerator waitnigTillEbd () {
yield return new WaitForSeconds (audioLenght + 1f);
curentSoundInfo.eventOnSound.Invoke ();
}
[System.Serializable]
public class soundInfo {
public string name;
public int ID;
public AudioClip clipToPlay;
public UnityEvent eventOnSound;
}
}
解决方案
好吧,我自己找到了解决方案。这是创建声音列表的最终结果,每个声音都单独附加了事件 onstop,也可以通过另一个事件和类的 ID 播放,供任何需要它的人使用
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
[RequireComponent(typeof(AudioSource))]
public class MainAudioManager : MonoBehaviour {
public List<soundInfo> soundList = new List<soundInfo>();
AudioSource audioSource;
soundInfo curentSoundInfo;
float audioLenght;
void Start () {
audioSource = gameObject.GetComponent<AudioSource> ();
}
public void SetAudioToPlay (int ID) {
for (int i = 0; i < soundList.Count; i++) {
if (soundList [i].ID == ID) {
curentSoundInfo = soundList [i];
StartCoroutine(playSequencely());
return;
}
}
}
IEnumerator playSequencely () {
yield return null;
for (int cnt = 0; cnt < curentSoundInfo.clipsToPlay.Length; cnt++) {
audioSource.clip = curentSoundInfo.clipsToPlay [cnt];
audioSource.Play ();
while (audioSource.isPlaying) {
yield return null;
}
}
//Debug.Log ("Last Audio Is Playing");
curentSoundInfo.onStop.Invoke ();
}
}
[System.Serializable]
public class soundInfo {
public string name;
public int ID;
[TextArea (2, 8)] public string About;
public AudioClip[] clipsToPlay;
//public float delayBetween;
public UnityEvent onStop;
}
推荐阅读
- php - 在php中更改数据表td值
- c++ - 模板模板参数推演指南
- android - 如何在flutter中访问json列表
- python-3.x - 聚合时获取一个热编码值的比例 - Pandas
- javascript - 如何显示来自另一个网站的交互式图形?
- ubuntu - 树莓派上的 Ubuntu 映像:重启/关机后 Wifi 需要很长时间才能连接(ssh)
- wpf - 使用带有 IsNavigationTarget 的 Prism 处理嵌套视图,可以返回 false
- regex - 匹配只有两个结束字符的域的正则表达式?
- spring - BeanDefinitionStoreException: 无法解析配置类...因为它不存在
- c++ - 使用列表初始化器与构造器的复杂<>?