0

I’m trying to get a callback at a given point in an AKPlayer’s file playback (currently, just before the end). I see the Apple docs on addBoundaryTimeObserver(), which would work, but it doesn’t seem to be accessible from AKPlayer (I guess an AVAudioPlayerNode vs AVPlayer thing). Any suggestions? I see a few callbacks in AVAudioPlayerNode… maybe I could determine the buffer based on the desired time and use dataConsumed?

The goal is to trigger another event just before the file finishes playing (there is a callback on completion, but obviously that's too late).

If anybody has done something similar, or knows of something similar (a gist, etc), that would be great.

jbm
  • 1,248
  • 10
  • 22

1 Answers1

0

There's an AudioKit playground called AKPlaygroundLoop that shows you how to call an arbitrary handler periodically, based on CADisplayLink. In your handler you could check the AKPlayer's currentTime and if it's close to the end (say 1 second before) you could trigger whatever event you want.

This is a rough outline:

var player: AKPlayer!
var loop: AKPlaygroundLoop!

func play() {
    // ...
    playgroundLoop = AKPlaygroundLoop(frequency: 10.0, handler: myHandler)
}

func myHandler() {
    if player.currentTime >= player.duration - 1.0 {
        // trigger some event
    }
}

See also this answer for advice on how to synchronize events with AudioKit.

vindur
  • 436
  • 4
  • 7
  • Interesting, thanks for pointing this out. Could work, but it seems like a weird use of CADisplayLink, which is concerned with synchronizing an update to the screen's refresh rate. I'm not sure it would be more appropriate than some other polling mechanism. My intention was to avoid polling, and use a callback instead. For my immediate task I tried something with `asyncAfter', but keeping timings straight was too fussy. I've worked around the whole issue for now. – jbm Dec 30 '20 at 20:33
  • An alternative would be to use [AKSequencer](https://audiokit.io/docs/Classes/AKSequencer.html) with an [AKCallbackInstrument](https://audiokit.io/docs/Classes/AKCallbackInstrument.html) and create an event at the time position you want. See [this answer](https://stackoverflow.com/a/61545391/2679386) on how to connect an AKCallbackInstrument to an AKSequencer track. – vindur Mar 19 '21 at 20:05