播放时音频播放器的持续时间发生变化 [英] Audio player duration changes while playing

查看:82
本文介绍了播放时音频播放器的持续时间发生变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在播放音频文件之前,我先听一段音频文件的持续时间:

When I take the duration of an audio file before playing it with:

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

我得到例如16.71s的持续时间.然后在播放时每隔0.2s采样一次时,持续时间会改变.它每1.2到1.6秒更改为:16.71s,17.02s,17.23s,17.33s,17.38s,17.43s,17.38s,17.29s,17.31s,然后在最后2.5秒保持在17.51s.因此它会上下波动.

I get a duration of for example 16.71s. Then when taking samples every 0.2s while playing, the duration changes. It changes every 1.2 to 1.6 seconds to: 16.71s, 17.02s, 17.23s, 17.33s, 17.38s, 17.43s, 17.38s, 17.29s, 17.31s, then stays at 17.51s for the last 2.5 seconds. So it goes up and down.

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

I sample in a method that updates a slider position, and also shows the elapsed time and total duration. You can imagine it looks really weird to see the duration (which is int-truncated) go from 16 to 17 while playing. Additionally, the slider position will be off with all this drifting.

有人知道为什么会这样吗?

Does anyone have an idea why this is?

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

Now that we're talking about duration: Does anyone know why audio player.duration can return values that are about twice the actual duration when [audioPlayer prepareToPlay] is omitted?

推荐答案

基于到目前为止已解码的文件数量,avaudioplayer的duration方法返回的持续时间是对文件总持续时间的最佳估计.这就是为什么随着时间的推移,持续时间会不断完善的原因.

The duration returned by avaudioplayer's duration method is a best estimate of the total duration of the file based on how much of the file has been decoded so far. That's why the duration continues to get refined as you check it over time.

为了获得更好的时间,我使用了AVAsset的工期方法.它解释了这里发生了什么更好的事情:

In order to get a better time, I use AVAsset's duration method. It explains what is going on a bit better here:

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

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

If you specify providesPreciseDurationAndTiming = YES, then AVAsset will decode the file if needed to determine its duration with accuracy. If the decode time is too long for your use, you can disable it.

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

In my situation, I use the AVURLAsset subclass:

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

这篇关于播放时音频播放器的持续时间发生变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆