AVAudioPlayer Duration Changing

2019-08-28 02:46发布

My app uses AVAudioPlayer to play music files. It also has a UISlider to adjust where in the song it is playing back. However, there is an odd bug with the UISlider in that it seems to be changing the audioPlayer's duration.

When a song is started, as part of the process, values are set like so:

audioPlayer.currentTime = 0;
seekingSlider.maximumValue = [audioPlayer duration];
seekingSlider.value = audioPlayer.currentTime;

This works no problem. I then have an NSTimer that updates the playedTime and the seekingSlider. That also doesn't seem to have a problem. When a user changes the seeking, that then goes to the following seekingChanged function.

- (IBAction)seekingChanged:(id)sender
{
    audioPlayer.currentTime = seekingSlider.value;
    [self updatePlayedTimeLabel:audioPlayer.currentTime];
}


- (void)updatePlayedTimeLabel:(NSTimeInterval)time {
    playedTime.text = [NSString stringWithFormat:@"%d:%02d", (int)time / 60, (int)time % 60, nil];
    [playedTime sizeToFit];
}

Note that at no point do I write to audioPlayer.duration. I only read from it in the beginning and at various NSLog statements to debug what's happening. To my surprise, it changes. Here's one sample output at the beginning of a song, just after setting the values:

after setting, seeking slider is at 0.000000 / 278.981384, audioplayer is at 0.000000 / 278.981375

Here's another one, just after pausing it 55 seconds in:

pausing, seeking slider is at 55.884716 / 278.981384, audioplayer is at 55.946236 / 274.689354

Is there a known bug with audioPlayer changing the duration? This manifests itself as a bad bug when a user changes the slider and it moves to the next song because audioPlayerDidFinishPlaying is called.

1条回答
地球回转人心会变
2楼-- · 2019-08-28 03:29

Under certain compression formats, the audio player may change its estimate of the duration as it learns more and more about the song by playing (and hence decoding) more and more of it. There's a similar observation here:

Audio player duration changes while playing

I think you will need to adjust the duration expressed by the slider in order to match the audio player's changes in its knowledge of the duration.

查看更多
登录 后发表回答