/// <summary> /// Play the given Sound and attribute it the given name. (Either sound or list name) /// </summary> /// <param name="sound"></param> /// <param name="name"></param> /// <param name="onEndPlay"></param> private void PlaySound(Sound sound, string name, Action onEndPlay = null) { AudioSource source; //Get a source, enables it. source = GetAvailableAudioSource(); source.enabled = true; //Encapsulate in the PlayingSound class PlayingSound playing = new PlayingSound(); playing.Name = name; playing.Sound = sound; playing.Source = source; playing.OnPlayEnd = onEndPlay; //Remember has currently playing currentlyPlaying.Add(playing); if (!sound.Loop) { //Play it once if not looped. StartCoroutine(_PlaySoundOnce(playing)); } else { //Play it indefinitively. sound.LoadIn(source); source.Play(); } }
/// <summary> /// Return true if the sound with the given name is played, and if true, /// load its PlayingSound class in the out var. /// </summary> /// <param name="name"></param> /// <param name="play"></param> /// <returns></returns> private bool IsCurrentlyPlaying(string name, out PlayingSound play) { play = null; foreach (PlayingSound playing in currentlyPlaying) { if (playing.Name.Equals(name)) { play = playing; return(true); } } return(false); }
/// <summary> /// Play the given sound once, then free the audio source and invoke optional OnPlayEnd action. /// </summary> /// <param name="playing"></param> /// <returns></returns> private IEnumerator _PlaySoundOnce(PlayingSound playing) { AudioSource source = playing.Source; Sound sound = playing.Sound; sound.LoadIn(source); source.loop = false; source.Play(); yield return(new WaitForSeconds(source.clip.length)); //Interrupt if it was removed from the current play list if (!IsCurrentlyPlaying(playing)) { yield break; } FreeAudioSource(source); playing.OnPlayEnd?.Invoke(); }
/// <summary> /// Return true if the sound is currently played. /// </summary> /// <param name="play"></param> /// <returns></returns> private bool IsCurrentlyPlaying(PlayingSound play) { return(currentlyPlaying.Contains(play)); }
/// <summary> /// Return true if the sound with the given name or list name is being played. /// (The name that was used to play the sound) /// </summary> /// <param name="name"></param> /// <returns></returns> public bool IsCurrentlyPlayed(string name) { PlayingSound play = null; return(IsCurrentlyPlaying(name, out play)); }