AudioKit play notes on external MIDI keyboard

Viewed 61

I use AudioKit to play notes via Mixer() and Sequencer(). I would like change the output node to an external MIDI device (e.g. piano) but can't figure out how to set the output node correctly. For illustration, following code plays some notes on the device (iOS) itself. Any help is greatly appreciated.

import AudioKit
import AudioKitEX

struct SongInfoView: View {
  let engine = AudioEngine()
  let sampler = MIDISampler(name: "MIDISampler")
  var mixer = Mixer()
  var sequencer = Sequencer()

  func playMIDI() {
    do {
        try sampler.loadSoundFont("Grand Piano", preset: 0, bank: 0)
           print("Soundfont Grand Piano loaded")
    } catch {
        print("Error loading Grand Piano soundfont")
    }
    
    mixer.addInput(sampler)
    
    let track = sequencer.addTrack(for: sampler)
    track.targetNode = sampler
    track.loopEnabled = false
            
    track.sequence.add(noteNumber: 80, velocity: 100, position: 0, duration: 1)
    track.sequence.add(noteNumber: 81, velocity: 100, position: 1, duration: 1)
    track.sequence.add(noteNumber: 82, velocity: 100, position: 2, duration: 1)
                
    track.tempo = 60
            
    for track in sequencer.tracks {
        track.targetNode = mixer
    }
            
    try? engine.stop()
    engine.output = mixer
            
    do {
        try engine.start()
        print("AudioKit engine started")
    } catch {
        Log("AudioKit did not start! \(error)")
    }
    print(engine.connectionTreeDescription)

    sequencer.playFromStart()
  }
...
}

I assume the solution evolves around:

midi = MIDI()
midi.createVirtualPorts()
midi.createVirtualOutputPorts()
midi.openInput()
midi.openOutput()
0 Answers
Related