Intro to looping music in single audio clip?

I would like to know how to get an audio clip with both an intro and loop to work properly in Unity.

Here’s my idea visualized. The yellow part is the loop. The red area is the intro.

And here’s the audio used.

One way of doing this is setting AudioSource.timeSamples to the sample that you want to go to.

You need 2 pieces of information about the audio track to make a song loop, with or without an intro:

  1. How long does the loop last?
  2. When does the first loop finish in the audio track?

In the case of an audio track without any intro, 1 and 2 are the same. If there is an intro, then 2 will be greater than 1. Once you reach the end of the first loop, subtract the length of the loop from the current time of audio. That will place you back at the beginning of the first loop.

Here is a sample implementation that I wrote for a rhythm game library. The Update function is the important part. It does exactly what I explained above (with the addition of converting seconds to samples).

I have the same problem as you so I made a solution called Introloop. You provide it 2 boundary points and one audio file then the script will handle it.

In your case, the first point is the seam between red and yellow and the second point is at the end of yellow. You should render a bit more at the end though, by copy pasting the yellow section after red to the end for about 1 second so if the schedule lag by some reason, you won’t hear the silence. And also for compression artifact problem that a gap will be add to the end.

If you want to implement it yourself, the idea is you should have 2 AudioSources and do a baton-passing continuously. And you should use AudioSettings.dspTime-related function like AudioSource.PlayScheduled , AudioSource.SetScheduledEndTime and AudioSource.SetScheduledStartTime instead of coroutines or PlayDelayed.

The first one play intro and immediately call SetScheduledEndTime on it to stop at the passing point. Where the second one is being SetScheduledStartTime-ed to start at that exact time, and SetScheduledEndTime to stop at the loop’s end too. When the transfer is successful, the just-stopped first one should be waiting at the loop end point with SetScheduledStartTime to prepare for the next loop. Repeat for infinite loop. In my case I used 4 AudioSources to handle cross-fading between music with intro. (that’s 2 pair of AudioSource)

If you want to pause the music, things will get a bit more complicated because you need to cancel all the already-scheduled audio source, and reschedule them all on resume with regard to what time you are on now on the audio clip before pause. (On the development of my script I remembered having much trouble in pausing-resuming)