- Home /
Audio/c#/unity Can i control the duration by time ?
Hello,
I need to control the duration of AudioClip by time. The sound must loop as long as the function does not stop it an example:
 void playWhile(float time){
 if(time >= 0){
 gameobject.getcompenant<audiosource>().play();
 }else{
 gameobject.getcompenant<audiosource>().stop(); // Stops it immediately, Do not wait until the end of the sound
 
 }
 
 }// The sound must loop as long as the function does not stop it
Thank, and sorry for my english (i m french)
               Comment
              
 
               
              the function as you have it writen is going to complete in one frame. are you simply looking to set a timer for how long to play a sound?
 
               Best Answer 
              
 
              Answer by jdean300 · May 21, 2017 at 03:44 AM
It seems like you want to stop an audio clip after a certain amount of time. You could do something like this:
 public void PlayForTime(float time)
 {
     GetComponent<AudioSource>().Play();
     Invoke("StopAudio", time)
 }
 
 private void StopAudio()
 {
     GetComponent<AudioSource>().Stop();
 }
Now if you call PlayForTime(5f) the audio will play for 5 seconds and then be stopped.
Your answer
 
 
              koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                