0

My goal is to receive MIDI events from an external keyboard and trigger the appropriate notes on a sampler. I wasn't able to come up with a working solution so far and I haven't found an example covering that exact usecase.

My code so far (macOS, Swift):

let audioEngine = AudioEngine()
let sampler = MIDISampler()
audioEngine.output = sampler
        
try! audioEngine.start()
try! sampler.loadEXS24("...")

sampler.enableMIDI()

When I manually trigger a note via sampler.receivedMIDINoteOn, I hear a sound. The MIDI part itself also works - I hooked up a MIDIListener and logged the noteOn events. However I don't understand how to connect both parts together.

DeerMichel
  • 51
  • 8

1 Answers1

0

Add a MidiListener Delegate like this:

class YourSamplerConductor: ObservableObject, MIDIListener

This will in give you an error and when you click over the "X" you'll have the option to import the MidiListener delegate methods.

This is how I add the listener in my init method:

let midi = MIDI.sharedInstance
midi.openInput()
midi.addListener(self)

Then pass your note info to the delegate methods.

func receivedMIDINoteOn(noteNumber: MIDINoteNumber, velocity: MIDIVelocity, channel: MIDIChannel, portID: MIDIUniqueID?, timeStamp: MIDITimeStamp?) {
    sampler.play(noteNumber: noteNumber, velocity: velocity, channel: channel)
}
Willeke
  • 14,578
  • 4
  • 19
  • 47
Nick C.
  • 226
  • 1
  • 4
  • That works, sure, but I thought there is maybe a more elegant way rather than mapping callbacks to the sampler manually? – DeerMichel Feb 13 '22 at 20:09
  • If you search for "receivedMIDINoteOn" through AudioKit's other repos you'll see where they do the manual mapping similar to this. The MidiListener doesn't infer how the midi events should be used. That allows you to be more flexible with these events if you want to do things like play multiple instruments from one midi event, apply a local note transpose value, or pass a constant velocity. – Nick C. Feb 14 '22 at 13:00
  • I see, but then I don't understand what the "sampler.enableMIDI()" method is used for? – DeerMichel Feb 14 '22 at 19:48