Audio player duration changes while playing

不问归期 提交于 2019-12-11 03:22:07

问题


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;

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.

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?

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?


回答1:


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.

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

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.

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


来源:https://stackoverflow.com/questions/16246088/audio-player-duration-changes-while-playing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!