Skip to content

Instantly share code, notes, and snippets.

@genedelisa
Created November 11, 2014 14:13
Show Gist options
  • Save genedelisa/7b440f128db96c3ba66f to your computer and use it in GitHub Desktop.
Save genedelisa/7b440f128db96c3ba66f to your computer and use it in GitHub Desktop.
Looping an iOS/OSX AudioToolbox MusicTrack in Swift
func loopTrack(musicTrack:MusicTrack) {
var trackLength = getTrackLength(musicTrack)
println("track length is \(trackLength)")
setTrackLoopDuration(musicTrack, duration: trackLength)
}
func getTrackLength(musicTrack:MusicTrack) -> MusicTimeStamp {
//The time of the last music event in a music track, plus time required for note fade-outs and so on.
var trackLength:MusicTimeStamp = 0
var tracklengthSize:UInt32 = 0
var status = MusicTrackGetProperty(musicTrack,
UInt32(kSequenceTrackProperty_TrackLength),
&trackLength,
&tracklengthSize)
if status != OSStatus(noErr) {
println("Error getting track length \(status)")
CheckError(status)
return 0
}
println("track length is \(trackLength)")
return trackLength
}
/*
The default looping behaviour is off (track plays once)
Looping is set by specifying the length of the loop. It loops from
(TrackLength - loop length) to Track Length
If numLoops is set to zero, it will loop forever.
To turn looping off, you set this with loop length equal to zero.
*/
func setTrackLoopDuration(musicTrack:MusicTrack, duration:MusicTimeStamp) {
println("loop duration to \(duration)")
//To loop forever, set numberOfLoops to 0. To explicitly turn off looping, specify a loopDuration of 0.
var loopInfo = MusicTrackLoopInfo(loopDuration: duration, numberOfLoops: 0)
var lisize:UInt32 = 0
var status = MusicTrackSetProperty(musicTrack, UInt32(kSequenceTrackProperty_LoopInfo), &loopInfo, lisize )
if status != OSStatus(noErr) {
println("Error setting loopinfo on track \(status)")
CheckError(status)
return
}
}
// or if you have a sequence as an ivar, you can do something like this
func setTrackLoopDuration(duration:Float) {
var track:MusicTrack = nil
var status = MusicSequenceGetIndTrack(self.musicSequence, 0, &track)
CheckError(status)
setTrackLoopDuration(track, duration: MusicTimeStamp(duration))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment