Search Unity

Audio Question on how to do triggers with audio files

Discussion in 'Audio & Video' started by lino49, Dec 9, 2020.

  1. lino49

    lino49

    Joined:
    Dec 9, 2020
    Posts:
    2
    Hi,

    I wanted to know how to start events on Unity triggered by audio.

    Like, for example, a music starts playing and after a certain amount of time has passed or a certain part of the music has passed or a certain note has played, it triggers something.

    Or the other way around, a certain event in the game triggers an audio. Like the character passed a gate, pressed a button and it can trigger a different audio. I saw there's the FMOD asset that can work for starting a music with different parameters, but is there something better?
     
  2. m00nandvenus46

    m00nandvenus46

    Joined:
    Nov 18, 2020
    Posts:
    36
    Use coroutines. They are not depend on the other code because doesn't lay in the only one time frame. yield keyword stops it for the time (seconds) or for the next frame. Fake multithreading. Coroutine divides itself to code parts. After assigning this script to the object in the scene place audio file to the project, add AudioSource component in inspector to the object and drug SerializeField parameters to empty cells. You may start coroutine in any code point when the event occurs. It will independently runing awhile. You may start coroutine inside other coroutine. Depend on what do you need exactly - do something when time comes (note played just now on the 3rd second and then wakes up a coroutine).

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4.  
    5. public class Test : MonoBehaviour
    6. {
    7.     public AudioClip ClipOrShortSound;
    8.     [SerializeField] public AudioSource Source;
    9.     float Volume = 1.0f;
    10.  
    11.     void Awake()
    12.     {
    13.         Source = GetComponent<AudioSource>();
    14.     }
    15.  
    16.     void Start()
    17.     {
    18.         StartCoroutine(StartMusic());
    19.     }
    20.  
    21.     void OnMouseDown()
    22.     {
    23.         Debug.Log("Hit");
    24.     }
    25.  
    26.     public IEnumerator StartMusic()
    27.     {
    28.         yield return new WaitForSeconds(1f); // wait    
    29.         Source.PlayOneShot(ClipOrShortSound, Volume); // play  
    30.         yield return null;   // wait for next frame and end execution
    31.     }
    32. }