Search code examples
iosavfoundationavaudioplayer

How to call method when AVAudioPlayer reaches a certain playback time?


I'm trying to perform an action when the playback reaches a certain time. I can't find any delegate methods or examples of how to do this. How can I call a method when the playback reaches a certain point?


Solution

  • That should help you addBoundaryTimeObserverForTimes:queue:usingBlock:

    Requests the invocation of a block when specified times are traversed during normal playback.

    Objective C:

    - (id)addBoundaryTimeObserverForTimes:(NSArray<NSValue *> *)times 
                                    queue:(dispatch_queue_t)queue 
                               usingBlock:(void (^)(void))block;
    

    Swift:

    func addBoundaryTimeObserver(forTimes times: [NSValue], 
                           queue: DispatchQueue?, 
                           using block: @escaping () -> Void) -> Any
    

    Usage:

    _ = self.player.addBoundaryTimeObserver(forTimes: times, queue: DispatchQueue.main, using: {
        [weak self] time in
        // Your code goes here
    })