Play Audio at Random Spot in File

Hello,

I am looking to create a level in which I have a fairly long background music track (maybe around 40 minutes, which I intend to loop). I want to be able to start the level and have the music track start playing at a random time - such as at the beginning, or two minutes in, or ten minutes in, or thirty minutes in, or whatever.

I am wondering if there is a script or a method for doing this. I have not been able to figure it out myself and have not been able to find existing documentation about it.

Any ideas?

Thanks!

I’ll assume that you’ve got an audiosource component already setup, with an audioclip assigned, and loop enabled. You should also disable playonawake on the audiosource.
Then drag that audiosource onto the script source field.

    public AudioSource source;
 
    void Start()
    {
        source.time = Random.Range(0f, source.clip.length);
        source.Play();
    }
4 Likes

Fantastic! Thank you so much. I will try this; looks very promising and straightforward!

Yes, this works great. I love it. Thank you again.