播放时音频播放器持续时间更改

mea*_*ers 3 iphone avaudioplayer ios

当我在播放音频文件之前获取它的持续时间时:

audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
...
[audioPlayer prepareToPlay];
duration = audioPlayer.duration;
Run Code Online (Sandbox Code Playgroud)

我得到例如 16.71s 的持续时间。然后在播放时每 0.2 秒采样一次时,持续时间会发生变化。它每 1.2 到 1.6 秒改变为:16.71s, 17.02s, 17.23s, 17.33s, 17.38s, 17.43s, 17.38s, 17.29s, 17.31s, 然后停留在最后 17.51.5 秒 所以它会上升和下降。

我在更新滑块位置的方法中进行了示例,还显示了经过的时间和总持续时间。您可以想象在播放时看到持续时间(整数截断)从 16 变为 17 看起来真的很奇怪。此外,随着所有这些漂移,滑块位置将关闭。

有谁知道这是为什么?

现在我们在谈论持续时间:有谁知道为什么audio player.duration[audioPlayer prepareToPlay]省略时返回的值大约是实际持续时间的两倍?

小智 5

avaudioplayer 的持续时间方法返回的持续时间是根据到目前为止文件的解码量对文件总持续时间的最佳估计。这就是为什么随着时间的推移,持续时间会不断得到完善。

为了获得更好的时间,我使用了 AVAsset 的持续时间方法。它更好地解释了这里发生的事情:

https://developer.apple.com/library/mac/documentation/AVFoundation/Reference/AVAsset_Class/Reference/Reference.html#//apple_ref/occ/instp/AVAsset/duration

如果您指定providesPreciseDurationAndTiming = YES,则AVAsset 将在需要时解码文件以准确确定其持续时间。如果解码时间太长而无法使用,您可以禁用它。

在我的情况下,我使用 AVURLAsset 子类:

            AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:localURL options:[NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithBool:YES], AVURLAssetPreferPreciseDurationAndTimingKey, nil]];
            float t = CMTimeGetSeconds(asset.duration);
Run Code Online (Sandbox Code Playgroud)