For AVAudioPlayer, there is corresponding AVAudioRecorder. For AVMIDIPLayer, I found nothing for recording from the system's active MIDI input device.
Can I record midi events from the system’s active input midi device, without resolving to low level CoreMidi?
After configuring AVAudioUnitSampler with just a few lines of code,
import AVFoundation
var engine = AVAudioEngine()
let unit = AVAudioUnitSampler()
engine.attach(unit)
engine.connect(unit, to: engine.outputNode, format: engine.outputNode.outputFormat (forBus:0))
try! unit.loadInstrument(at:sndurl) //url to .sf2 file
try! engine.start()
I could send midi events programmatically.
// feeding AVAudioUnitMIDIInstrument with midi data
let range = (0..<100)
let midiStart = range.map { _ in UInt8.random(in: 70...90) }
let midiStop = [0] + midiStart
let times = range.map { _ in TimeInterval.random(in: 0...100) * 0.3 }
for i in range {
DispatchQueue.main.asyncAfter(deadline: .now()+TimeInterval(times[i])){
unit.stopNote(midiStop[i], onChannel: 1)
unit.startNote(midiStart[i], withVelocity: 127, onChannel: 1)
}
}
But instead, I need to send midi events from a midi instrument, and tap to them for recording.