OGeek|极客世界-中国程序员成长平台

标题: iphone - 播放时音频播放器持续时间发生变化 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 02:26
标题: iphone - 播放时音频播放器持续时间发生变化

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

audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
...
[audioPlayer prepareToPlay];
duration = audioPlayer.duration;

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

我以一种更新 slider 位置的方法进行采样,并显示耗时和总持续时间。您可以想象,在播放时看到持续时间(被 int 截断)从 16 变为 17 看起来真的很奇怪。此外,随着所有这些漂移, slider 位置将关闭。

有人知道这是为什么吗?

现在我们正在讨论持续时间:有谁知道为什么 audio player.duration[audioPlayer prepareToPlay] 为省略了吗?



Best Answer-推荐答案


avaudioplayer 的 duration 方法返回的持续时间是根据到目前为止已解码文件的多少来对文件总持续时间的最佳估计。这就是为什么随着时间的推移检查持续时间会不断完善的原因。

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

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);

关于iphone - 播放时音频播放器持续时间发生变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16246088/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4