AVAudioPlayer播放到一定时间后如何调用方法?

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

我正在尝试在播放到特定时间时执行操作。我找不到任何委托方法或如何执行此操作的示例。如何在播放到某个点时调用方法?

那应该对你有帮助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

用法:

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

添加更多细节。

您可以 addBoundaryTimeObserver(forTimes:queue:using:) 特定时间或使用 addPeriodicTimeObserver(forInterval:queue:using:) 定期间隔。

 // for specific time
func addTimeObserver() {
    var times = [NSValue]()

    var currentTime = kCMTimeZero // make your time here

        times.append(NSValue(time:currentTime))

    // Queue on which to invoke the callback
    let mainQueue = DispatchQueue.main

    // Add time observer
    timeObserverToken =
        player.addBoundaryTimeObserver(forTimes: times, queue: mainQueue) {
            [weak self] time in
            // Update UI
    }
}

在正常播放期间每半秒触发一次

func addPeriodicTimeObserver() {
// Invoke callback every half second
let interval = CMTime(seconds: 0.5,
                      preferredTimescale: CMTimeScale(NSEC_PER_SEC))

let mainQueue = DispatchQueue.main

timeObserverToken =
    player.addPeriodicTimeObserver(forInterval: interval, queue: mainQueue) {
        [weak self] time in
        // update UI
}}