Hello,
I am developing a macOS app using AudioToolbox's MusicSequence and MusicPlayer APIs to play Standard MIDI Files.
The MIDI playback works correctly and I can hear sound from the external MIDI device. However, the user callback registered via MusicSequenceSetUserCallback is never invoked during playback.
Details:
- Callback registration returns no error.
- MusicPlayer is properly started and prerolled.
- The callback is defined as a global function with the correct @convention(c) signature.
- I have tried commenting out MusicTrackSetDestMIDIEndpoint to avoid known callback suppression issues.
- The clientData pointer is passed and correctly unwrapped in the callback.
- Minimal reproducible example shows the same behavior.
Environment:
- macOS version: [Tahoe 26.2]
- Xcode version: [26.2]
Is it expected that MusicSequenceSetUserCallback callbacks may not be called in some cases?
Are there additional steps or configurations required to ensure the callback is triggered during MIDI playback?
Thank you for any advice or pointers.
Execute playTest() in the viewDidLoad() method of the ViewController.
extension ViewController {
private func playTest() {
NewMusicSequence(&sequence)
if let midiFileURL = Bundle.main.url(forResource: "etude", withExtension: "mid") {
MusicSequenceFileLoad(sequence!, midiFileURL as CFURL, .midiType,MusicSequenceLoadFlags())
NewMusicPlayer(&player)
MusicPlayerSetSequence(player!, sequence!)
MusicPlayerPreroll(player!)
let status = MusicSequenceSetUserCallback(sequence!, musicSequenceUserCallback, Unmanaged.passUnretained(self).toOpaque())
if status == noErr {
print("Callback registered successfully")
} else {
print("Callback registration failed: \(status)")
}
MusicPlayerStart(player!)
} else {
print("MIDI File Not Found")
}
}
}
The callback function was generated by Xcode and defined outside the ViewController.
func musicSequenceUserCallback(
clientData: UnsafeMutableRawPointer?,
sequence: MusicSequence,
track: MusicTrack,
eventTime: MusicTimeStamp,
eventData: UnsafePointer<MusicEventUserData>,
startSliceBeat: MusicTimeStamp,
endSliceBeat: MusicTimeStamp
) {
print("User callback fired at eventTime: \(eventTime)")
if let clientData = clientData {
let controller = Unmanaged<ViewController>.fromOpaque(clientData).takeUnretainedValue()
// Example usage to prove round-trip works (avoid strong side effects in callback)
_ = controller.view // touch to silence unused warning if needed
print("Callback has access to ViewController: \(controller)")
} else {
print("clientData was nil")
}
}