Search code examples
iosobjective-cavaudioplayer

AVAudioPlayer returns wrong file duration


I use AVAudioPlayer for playing audio file and UISlider to show user current time. Firstly, it looked that everything is fine but I noticed that audio player returns wrong file duration. For example it returns me duration equals to 3.5sec but file durations is equal to 6 sec. in reality.

Do you know What can cause this problem?

Below you can see my code which return file duration:

- (NSTimeInterval)audioDurationAtURL:(NSURL *)url
{
   NSError *error;
   NSData *data = [NSData dataWithContentsOfURL:url];
   _audioPlayer = [[AVAudioPlayer alloc] initWithData:data error:&error];
   return _audioPlayer.duration;
}

Solution

    1. AVAudioPlayer appears to only returns the correct duration of a file when it is ready for play it, so try to check the length of the audio file after [_audioPlayer play];

    2. 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 - https://stackoverflow.com/a/16265186