audio reaction

Let say i have an audio and i want a gameobject to react to a certain point in the audio like if the audio is at 60% of it way or 10 second since the audio stated, how would i do this, if any scripts involve, please put them in c#

You can use the following:

public class AudioPlayer : MonoBehaviour
{

    public delegate void AudioStartHandler();

    public event AudioStartHandler;

    void Update()
    {
        if (condition()) //here check the conditions.
        {
            audio.Play();
            if (AudioStartHandler != null) AudioStartHandler();
        }
    }
}

And in the GameObject that wants to listen add:

public class AudioListener : MonoBehaviour
{
    void Start()
    {
        GetAudioPlayer().AudioStartHandler += Listen;
    }
    void Listen()
    {
        Debug.Log("The audio start");
        StartCoroutine(BlockWait());
    }

    IEnumerator Wait()
    {
        yield return new WaitForSeconds(10s); // the number of seconds
        Debug.Log("After 10 seconds!");
    }

}

The steps are:

  • Create a event that its fired when the audio start.
  • Listen to the event and delay 10 secs.

If you want to start at the 60% of the audio, pass the AudioSource.length and instead of wait for 10 sec, just wait for length * .6f

You can use AudioSource.time which returns a float value in seconds.

If you want something to happen in, for example, 10th second you can use something like this:

if(yourSource.isPlaying){
    if(yourSource.time == 10){
        // Do your reaction here
    }
}

you can try different approaches either. For example, for a percentage you can use AudioClip.length too, which also returns a float value.