Michael Krautsieder
Michael Krautsieder

Reputation: 123

How to send MIDI data from iOS to OS X over LE Bluetooth with Swift

Is there any tutorial which explains how to send MIDI data from an iOS Device to a mac using CABTMIDILocalPeripheralViewController()?

The connection works, but I don't know how I send the MIDI data. I googled about two hours and did not find anything. Maybe you can help me?

Upvotes: 4

Views: 1760

Answers (1)

Kevin
Kevin

Reputation: 1192

From Apple's documentation (and as you've discovered), all that the CABTMIDILocalPeripheralViewController dance does is make the networked MIDI Device available. It doesn't actually establish any MIDI connections to the device(s) that it discovers over the network.

After a connection is established, it simply appears as an ordinary MIDI device that any MIDI application can communicate with.

This means that you still have to handle the rest of your app's MIDI implementation. To do that, you have to use the CoreMIDI framework, which is somewhat cumbersome, especially in the world of Swift.

The following code illustrates how you can enumerate your available MIDI devices:

let numDevices = MIDIGetNumberOfDevices()
for ix in 1...numDevices {
    let dev = MIDIGetDevice(ix)  // `dev` is a MIDIDeviceRef
    print("Device \(ix) is \(dev)")  // so it shows up as a number here
    var deviceNameCF: Unmanaged<CFString>?  // the Swift equivalent of a pointer to a string
    let propertyNameErr = MIDIObjectGetStringProperty(dev, kMIDIPropertyName, &deviceNameCF)
    if (propertyNameErr != 0) {
        print("Error getting property: \(propertyNameErr)")
    } else {
        let deviceName = deviceNameCF!.takeRetainedValue() as? NSString
        print("Device name: \(deviceName!)")
    }
}

For debugging, you can add this to the doneAction handler shown in their example, or for something a bit more robust in production, you can use the doneAction handler to trigger your UI to refresh to show the newly available device(s).

Edit The PGMidi library is a convenient, light-weight, flexibly-licensed option for sending MIDI data to destinations, including those you connect to via Bluetooth.

Upvotes: 4

Related Questions