unity AudioSource播放完声音后要执行的函数或条件操
将脚本挂在要判断声音是否播放完毕的物体上
using System.Collections; using UnityEngine; using UnityEngine.Events; [RequireComponent(typeof(AudioSource))] public class AudioManager : MonoBehaviour { public static AudioManager instence = null; private AudioSource _audio; void Awake() { if (instence == null) { instence = this; } } void Start() { _audio = GetComponent<AudioSource>(); } void Update() { //按下键盘按钮A键执行函数播放语音 if (Input.GetKeyDown(KeyCode.A)) { PlayAudio(GameObject.GetComponent().clip) } } //接受音频文件和是否重复播放 public void PlayAudio(AudioClip clip, UnityAction callback = null, bool isLoop = false) { //获取自身音频文件进行播放并且不重复播放 _audio.clip = clip; _audio.loop = isLoop; _audio.Play(); //执行协成获取音频文件的时间 StartCoroutine(AudioPlayFinished(_audio.clip.length, callback)); } //执行协成函数 并且返回时间 private IEnumerator AudioPlayFinished(float time, UnityAction callback) { yield return new WaitForSeconds(time); //声音播放完毕后之下往下的代码 # region 声音播放完成后执行的代码 print("声音播放完毕,继续向下执行"); #endregion } }
补充:Unity 的 AudioSourse 播完的监听
最近涉及到 音频结束后的调用问题,unity 原生的音频组件 AudioSourse 没有功能,于是自己写了一个。
下面是代码:
using Assets.Scripts.Entities; using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class AudioSourceInfo { private float playTime = 0; public AudioSource AudioSource { get; private set; } public AudioState AudioState = AudioState.Idle; public Action AfterPlaying { get; set; } public int ID = 0; public AudioSourceInfo(GameObject go) { this.AudioSource = go.AddComponent<AudioSource>(); } public AudioClip Clip { get { return this.AudioSource.clip; } set { this.AudioSource.clip = value; playTime = 0; } } public bool Loop { get { return this.AudioSource.loop ; } set { this.AudioSource.loop = value; } } public float Volume { get { return this.AudioSource.volume; } set { this.AudioSource.volume = value; } } public void Play() { if (null == this.AudioSource) { return; } this.AudioState = AudioState.IsPlaying; this.AudioSource.Play(); } public void Pause() { if (null == this.AudioSource) { return; } if(this.AudioSource.isPlaying) { this.AudioState = AudioState.Pause; this.AudioSource.Pause(); } } public void Stop() { if (null == this.AudioSource) { return; } this.AudioState = AudioS【转自:http://www.1234xp.com/kt.html 转载请说明出处】tate.Stop; this.AudioSource.Stop(); if(AfterPlaying!= null) { this.AfterPlaying(); } } private void Update() { if (this.AudioSource != null && this.AudioSource.clip!= null && this.AudioState == AudioState.IsPlaying) { playTime += Time.fixedDeltaTime; if (playTime >= this.Clip.length) { playTime = 0; this.Stop(); } } } } public enum AudioState { Idle, IsPlaying, Pause, Stop, }
补充:Unity3d AudioSource如何监听播放完成并处理逻辑
想知道AudioSource什么时候播放完成并处理相关的逻辑,比如切换曲目,而unity又没有提供相应的事件
于是想到下面几种方案:
1、Update时时判断isPlaying
2、获取音频的播放长度,Invoke一下
后来查看api的时候突然想到,可以用协程啊。原理和Invoke一样,这应该是最好的方案了。
不过如果音频暂停掉了之后而又没有更新协程函数的话,问题就出现了。所以暂停的时候记得更新协程函数。
以上为个人经验,希望能给大家一个参考,也希望大家多多支持海外IDC网。如有错误或未考虑完全的地方,望不吝赐教。
【来源:海外服务器https://www.68idc.cn】