AVPlayer 播放准确的时间

AVPlayer play for exact amount of time

我想使用 AVPlayer 播放一个 mov 文件恰好 1 秒然后暂停它。

目前我正在播放 mov 然后设置一个定时器在 1 秒后暂停,如下所示。不幸的是,这似乎并不完全准确,而且有时 mov 播放的时间略短或长于 1 秒。请问有更准确的方法吗?

[self.player4 play];
[self performSelector:@selector(pausePlayer4:) withObject:nil afterDelay:1.0];

- (void)pausePlayer4:(NSTimer *)timer
{
    [self.player4 pause];
}

最好的方法是添加一个边界观察器在一秒后触发

    NSValue *endBoundary = [NSValue valueWithCMTime:CMTimeMakeWithSeconds(1.0, 300)];

    [self.player4 addBoundaryTimeObserverForTimes:@[endBoundary]
                                            queue:NULL
                                       usingBlock:^{
                                        [self.player4 stop];
                                        }];

    [self.player4 play];

即使您可以足够精确地触发事件,iOS 设备上的媒体播放也是在完全不同的进程(守护进程)中进行的,并且在执行 IPC 时始终存在延迟。

根据您的需要,最好构建一个 AVMutableComposition 来正好播放您 AVURLAsset 中一秒钟的内容,然后将乐曲分配给您的播放器。