Loop (Music)

From C# Gamedev Wiki

A Loop is a piece of music that repeats endlessly, often found in games as background music.

Full File Loop

In this implementation the music file loops from the start to the end, requiring the file to be trimmed neatly such that the start and end line up exactly. Very few songs are available in a trimmed format like this, so the developer may need to take a song and trim it manually using audio editing software like Audacity.

Partial File Loop

In this implementation the developer first defines a loop start and loop end within each song, and then has code that runs each frame to perform the looping.

TimeSpan LoopStart;
TimeSpan LoopEnd;

void UpdateMusicLoop()
{
    TimeSpan currentPlaybackPosition = GetPlaybackPosition();
    if (currentPlaybackPosition >= LoopEnd)
        PlayFrom(LoopStart + currentPlaybackPosition - LoopEnd);
}

The advantage of this implementation is that many files do not need to be edited to loop smoothly, the developer simply needs to define the loop start and end correctly. Make sure that the loop start and loop end are both on the same beat of the song.

If using this approach you must not use the end of the file as the loop end, since playback expects to continue slightly past the loop end point before returning to the start of the loop. If your file is already trimmed to the loop end, you may need to use audio editing software like Audacity to copy the first 1-2s after loop start to the end of the file in order to be safe.

Intro then Loop

Sometimes a developer wants to play an intro once before the loop starts. A great example of this is Zelda OoT, where pieces like Kokiri Forest and Gerudo Valley have very recognizable intros.

This can be easily done by playing the song from the intro, and then letting it automatically continue until the loop end at which point it will loop normally.

Transition between Loops

Sometimes a developer wants to progress from loop to loop in a file as a player makes progress in a level. A great example of this is Celeste.

This can be easily done by changing loop start and loop end to a different pair of values for a new loop as the player reaches new milestones in a level.