I am using the following code to receive MIDI events in a Swift Playground:
import Cocoa
import CoreMIDI
import XCPlayground
XCPSetExecutionShouldContinueIndefinitely(continueIndefinitely: true)
func notifyCallback(message:UnsafePointer<MIDINotification>,refCon:UnsafeMutablePointer<Void>)
{
println("MIDI Notify")
}
func eventCallback(pktlist:UnsafePointer<MIDIPacketList>, refCon:UnsafeMutablePointer<Void>, connRefCon:UnsafeMutablePointer<Void>)
{
println("MIDI Read")
}
var client = MIDIClientRef()
MIDIClientCreate("Core MIDI Callback Demo" as NSString, MIDINotifyProc(COpaquePointer([notifyCallback])), nil, &client)
var inPort = MIDIPortRef()
MIDIInputPortCreate(client, "Input port",MIDIReadProc(COpaquePointer([eventCallback])), nil, &inPort)
let sourceCount = MIDIGetNumberOfSources()
for var count:UInt = 0; count < sourceCount; ++count
{
let src:MIDIEndpointRef = MIDIGetSource(count)
MIDIPortConnectSource(inPort, src, nil)
}
I got this by translating working Objective-C code into what I think would be the correct Swift version.
It compiles and runs fine until one of the callbacks fires, e.g. when I unplug the MIDI device or hit one of its keys. I always get a BAD_EXEC.
Any ideas how to make this work or is Swift just not ready as some blog posts on the web state. Anything official from Apple that I overlooked that clearly states Swift is not ready yet for CoreMIDI callbacks?
Update 2015-03-10: The corresponding Objective-C code can be found at http://www.digital-aud.io/blog/2015/03/10/on-coremidi-callbacks/
Update 2021-06-25: I have written a programming tutorial on how to receive MIDI messages on Apple devices https://twissmueller.medium.com/midi-listener-in-swift-b6e5fb277406. There is a link in the tutorial where a complete Xcode-project with a sample application can be purchased.