Search Unity

Play audio for x seconds and pause for x seconds?

Discussion in 'Editor & General Support' started by Gibbonuk, Feb 13, 2017.

  1. Gibbonuk

    Gibbonuk

    Joined:
    Dec 10, 2013
    Posts:
    175
    Hi, I think ive just set out on a bad foot with this one and over complicated things.

    I have a short audio file that is a single monotone and I have it repeat so its like a ongoing "tone".

    However I want it to act like a "beep" so either pauses for n seconds or set the volume to 0 for n seconds either one is fine. However i want to to STOP for n seconds and then PLAY for n seconds and so on, n is variable which changes?

    Any pointers?

    Thanks
     
    Last edited: Feb 13, 2017
  2. Vectorbox

    Vectorbox

    Joined:
    Jan 27, 2014
    Posts:
    232
    Hi, have you considered using a coroutine ?. You could pass 'n' and use yieldreturnnewWaitForSeconds(n).
     
  3. IronLionZion

    IronLionZion

    Joined:
    Dec 15, 2015
    Posts:
    78
    Like Songroom said, a coroutine would get the job done.
    Do something like this:
    Code (CSharp):
    1. public float playTime = 0.5f;
    2. public float pauseTime = 0.5f;
    3. private AudioSource beep;
    4.  
    5. void Start()
    6. {
    7.     beep = GetComponent<AudioSource>();
    8.     StartCoroutine("PlayPauseCoroutine");
    9. }
    10.  
    11. IEnumerator PlayPauseCoroutine()
    12. {
    13.     while(true)
    14.     {
    15.         beep.Play();
    16.         yield return new WaitForSeconds(playTime);
    17.         beep.Pause(); // or beep.Stop()
    18.         yield return new WaitForSeconds(pauseTime);
    19.     }
    20. }