I am trying to implement an on-off switch in playing multiple AKPlayers. First, I have called two AKPlayers
, triggered by AKCallbackInstruments
in AKSequencer
.
When I turn the switch on, 1) two AKPlayers are assigned to AKMixer, 2) Audiokit starts, 3) Two tracks are added to AKSequencer, 4) Sequencer starts.
And when turn off, 1) two AKPlayers.stop()
, 2) sequencer.stop()
3) sequencer.deleteTrack(trackIndex: 0)
, sequencer.deleteTrack(trackIndex:1)
4) AudioKit.stop()
.
First on and off works successfully. But when I turn the switch on for the second time, the music is getting louder and louder, possibly because some midi tracks/sequencer tracks are not removed completely. Can anybody tell me what I’m missing here? Much appreciated. <3
To discover what is really happening here, you can log the contents of the tracks after each delete. For example:
for (i, track) in sequencer.tracks.enumerated() {
print("track: \(i)")
print(track.getMIDINoteData())
}
One possibility is that when you delete track 0, the tracks re-index themselves, which means the second delete call would have no effect.
Perhaps a safer and more predictable way to handle this would be to use track.clear()
rather than delete
. You can create the tracks you will need at the start and assign their output to the AKCallbackInstrument
only once at the setup stage. Then you can safely add notes to the tracks or clear events from the tracks as needed. Again, logging the track contents with track.getMIDINoteData()
will be helpful for debugging.
Also, I wouldn't recommend stopping and starting AudioKit more than you need to. Start AudioKit when you initialize your app, and leave it on unless you have a compelling reason to stop it.