Main Site Links Resources Tutorials
News VB Gaming Code Downloads DirectX 7
Contact Webmaster VB Programming Product Reviews DirectX 8
  General Multimedia Articles DirectX 9
      Miscellaneous

DirectMusic: Looping Playback
By: Jack Hoxley
Written: June 2000

Download: DM_Loop.Zip (9kb)


Looping music is very important for games; a piece of music may well last only 3 minutes, but they may well be playing the same level for 2 hours. This tutorial will show you two ways of looping; and it will also show you how to detect when the music is finished playing - which can cue you to shuffle the music/play the next track.

Method 1: The easy way
This involves checking every second whether or not the segment is still playing. If the SegmentState variables states that it is no longer playing you can start it again. This is useful for games as you aren't checking quite so often, and it really doesn't matter in a game how far through the piece you are. This method will also show you whether or not it as finished - so you can shoose to loop it or change the music track.

'This part goes in a timer, or in the main game loop
'The smaller the interval the less-of a delay
'there is before it picks up on changes.


If seg Is Nothing Then Exit Sub
If perf.IsPlaying(seg, segstate) Then
lblPlay.Caption = "Is it still playing: Yes!"
Else
lblPlay.Caption = "Is it still playing: No!"
'At this point we decide:
'A. Loop the same piece

MsgBox "We've got to the end; now we start again"
Set segstate = perf.PlaySegment(seg, 0, 0)
'B. Play another piece
End If

Method 2: The Even Easier Way
There is a simple function call built into DirectMusic that you can use to set loop points. You set two values, the start of the loop and the end of the loop - if these are set to the beginning and the end then it'll loop the whole track.

'Where Segment is already loaded, and is NOT playing.
Segment.SetLoopPoints 0, 0
'If they are both set to 0 then it will loop the entire segment.
Segment.SetRepeats ??
'This will set it to repeat ?? many times - which may well be useful to you.

Although these two methods could be used to repeat any segment of a piece of music; they're easy to use for repeating the whole segment.

You can download a working version from the top of the page; or from the downloads page.

DirectX 4 VB 2000 Jack Hoxley. All rights reserved.
Reproduction of this site and it's contents, in whole or in part, is prohibited,
except where explicitly stated otherwise.
Design by Mateo
Contact Webmaster