Search code examples
iosswiftaudiotoolboxcoremidi

Display current beat position in MusicSequence (coreMIDI/Swift)


I've created a music sequence using coreMIDI and AudioToolBox and would now like to display the current beat position of the looped sequence in the UI. If the loop is only four beats, I would like the display to toggle between 1,2,3,4 and return to 1 as the sequence loops (much like in the transport of a program such a Logic Pro). I've made a function that uses MusicSequenceGetBeatsForSeconds() to calculate the beats based on the amount of time (using CFAbsoluteTimeGetCurrent()) that has passed since play was pressed, but this keeps the value increasing linearly (on beat on of the next measure the display reads "5.0"). How do I read the current beat of the sequence?


Solution

  • Skip the end of track message; you can't rely on it.

    Instead create a MusicSequenceUserCallback. Then add a track to your sequence that holds user events. The actual data in the event doesn't matter.

    var event = MusicEventUserData(length: 1, data: (0xAA))
    let status = MusicTrackNewUserEvent(markerTrack, endBeat, &event)
    

    Then in the callback look for this arbitrary data value and do that thing you want to do.

    let d = eventData.memory
    if d.data == 0xAA {
    

    In Swift 2.2, the callback cannot be a closure. So make it a global function.