3

I'm trying to get the total duration of my mp3 file loaded from a remote URL, but it's returning NAN. I'm using AVPlayer (not AVAudioPlayer).

let duration = CMTimeGetSeconds((self.player?.currentItem?.asset.duration)!)
print(duration)// returns NAN
ZGski
  • 2,398
  • 1
  • 21
  • 34

3 Answers3

2

AvPlayer will always return Nan in playing remote mp3-s , you need to attach the duration with url in your model and hardcode it's duration in your server

Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
2

For a VOD content, you can get the duration with:

self.player.currentItem?.duration.seconds ?? 0.0

it is NAN when is a HLS live, you can access to Live point with:

guard let item = player.currentItem else {
    return
}

let seekableDuration = item.seekableTimeRanges.last?.timeRangeValue.end.seconds ?? 0.0

note: the live point changes as time go by

1

You should set an observer for the remote AVPlayerItem's status change.

self.statusObservation = nil  // remove observer for outdated items
self.statusObservation = self.avPlayer?.currentItem?.observe(\AVPlayerItem.status) { [weak self] item, _ in
    guard let self = self else { return }
    // prevent reading duration from an outdated item:
    guard item == self.avPlayer?.currentItem else { return }
    if item.status == .readyToPlay {
        item.duration.seconds  // the duration you need.
    }
}

Basically, when a remote AVPlayerItem has just being set, the AVPlayer knows nothing about the resource at all. It needs some time to retrieve the meta info, which includes the total duration.

iMoeNya
  • 672
  • 4
  • 11