Swift - AKMidi AudioKit 或 AKSequencer

Swift - AudioKit AKMidi to AKSequencer

我目前有一个应用程序使用 AKKeyboard 通过振荡器创建声音。每当弹奏键盘时,我也会得到 MIDI 数据。我想做的是从我收到的 MIDI 数据创建一个 AKSequence。

任何建议或指示将不胜感激,谢谢。

这是我的部分代码:

var bank = AKOscillatorBank()
var midi: AKMIDI!
let sequencer = AKSequencer()
let sequenceLength = AKDuration(beats: 8.0)

func configureBank() {
    AudioKit.output = bank

    do {
        try AudioKit.start()
    } catch {
        AKLog("AudioKit couldn't be started")
    }

    midi = AudioKit.midi
    midi.addListener(self)
    midi.openInput()
}

// AKKeyboard Protocol methods
func noteOn(note: MIDINoteNumber) {
    let event = AKMIDIEvent(noteOn: note, velocity: 80, channel: 5)
    midi.sendEvent(event)
    bank.play(noteNumber: note, velocity: 100)
}

func noteOff(note: MIDINoteNumber) {
    let event = AKMIDIEvent(noteOff: note, velocity: 0, channel: 5)
    midi.sendEvent(event)
    bank.stop(noteNumber: note)
}

// AKMIDIListener Protocol methods..
func receivedMIDINoteOff(noteNumber: MIDINoteNumber, velocity: MIDIVelocity, channel: MIDIChannel) {
    print("ReceivedMIDINoteOff: \(noteNumber), velocity: \(velocity), channel: \(channel)")
}

您实际上不需要直接从 AKMIDIEvents 构建序列。只需在调用 AKKeyboardView 的 noteOn 和 noteOff 方法时查询序列的 currentPosition,并基于此以编程方式将事件添加到音序器轨道。

过程基本与此相同(当然减去最后一步):

编辑 - 获取 noteOn 和 noteOff 时间以及持续时间:

// store notes and times in a dictionary:
var noteDict = [MIDINoteNumber: MIDITimeStamp]()

// when you get a noteOn, note the time
noteDict[currentMIDINote] = seq.currentPosition.beats

// when you get a noteOff
let endTime = seq.currentPosition.beats
if let startTime = noteDict[currentMIDINote] {
    let durationInBeats = endTime - startTime
    // use the startTime, duration and currentMIDINote to add event to track
    noteDict[currentMIDINote] = nil
}