user3533403
user3533403

Reputation: 71

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

Upvotes: 3

Views: 3729

Answers (4)

Pranavan SP
Pranavan SP

Reputation: 1865

I have faced a similar issue with Swift 5 Xcode 15.1, but I have resolved it by adding prepareToPlay() before the duration call. Example:

do {
   var player = try AVAudioPlayer(contentsOf: url)
   player.prepareToPlay()
   let duration = player.duration
} catch {
   NSLog("Error")
}

Upvotes: 0

Andy Korth
Andy Korth

Reputation: 361

To add a bit to TonyMkenu's answer, AVAsset is an alternative with the ability to give you a more accurate duration.

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

Upvotes: 3

Chris Amelinckx
Chris Amelinckx

Reputation: 4482

In my case, having added an audio file to a project then editing (making it longer or shorter) and then deleting and re-adding the file to the Xcode project was the problem. Essentially the project is caching the old file. To debug this I renamed the audio file to something else, added the new audio file to the project after which the duration reported by the player was always correct, before and after calling play.

Upvotes: 0

TonyMkenu
TonyMkenu

Reputation: 7667

  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

Upvotes: 3

Related Questions