AudioKit ios AKSequencer Not Restarting Playback Accurately

强颜欢笑 提交于 2019-12-06 09:30:15

There are a few confusing things in your code, so I'm not sure if this is your only issue, but minimally, every time you change the length of your sequence, you will need to call setLength() followed by enableLooping. Basically, by default (i.e., unless you explicitly set the length) the length of the sequence will be the length of the longest track in the sequence. In your 'playback' method you are adding track on top of track without removing the old ones so it has no way of knowing how long you intend the sequence to be.

Your 'playback' method is doing two distinct things (neither of which involves playback). You might want to break it up. You could have a setup() to do the things that only ever need to be done once (create the tracks, set their outputs, set up the callback) and a rewriteSequence() methods that gets called when you want to re-write the tracks. This way you can reuse your existing tracks rather than continuously creating new ones.

var metronomeTrack: AKMusicTrack!
var callbackTrack: AKMusicTrack!

    // call this just once at the start
    func setup() {
        metronomeTrack = sequencer.newTrack()
        metronomeTrack?.setMIDIOutput(click.midiIn)
        callbackTrack = sequencer.newTrack()
        callbackTrack?.setMIDIOutput(callbackInst.midiIn)

        callbackInst.callback = {status, noteNumber, velocity in
            guard status == .noteOn else { return }
            print("beat number: \(noteNumber + 1)")

        }
    }

    // call this each time you want to change the sequence
    func rewriteSequence() {
        metronomeTrack?.clear()
        callbackTrack?.clear()
        for steps in 0 ... Int(measuresRowOneValue) {
            metronomeTrack?.add(noteNumber: 60, velocity: 100, position: AKDuration(beats: Double(steps)), duration: AKDuration(beats: 0.5))
            callbackTrack?.add(noteNumber: MIDINoteNumber(steps), velocity: 100, position: AKDuration(beats: Double(steps)), duration: AKDuration(beats: 0.5))
        }

        // This will make sure it loops correctly:
        sequencer.setLength(AKDuration(beats: Double(measuresRowOneValue)))
        sequencer.enableLooping()
    }

I hope this helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!