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)

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.