I am trying to load the duration of an asset obtained from a URL. I have an AVPlayerItem and have tried using AVAsset too to get the duration. Here is my code:
private func play(url: String) async {
print("playing (url)")
guard let finalUrl = URL(string: url) else { return }
let playerItem = AVPlayerItem(url: finalUrl)
player = AVPlayer(playerItem: playerItem)
player?.volume = 1.0
player?.play()
playerInitialized = true
playerIsPlaying = true
let asset = AVAsset(url: finalUrl)
let audioDuration = asset.duration
let audioDurationSeconds = CMTimeGetSeconds(audioDuration)
print("TEST")
print(audioDuration)
print(audioDurationSeconds)
do {
let durationTest = try await asset.load(.duration)
print("FETCHED DURATION SHOULD BE:")
print(durationTest.seconds)
print(durationTest)
if durationTest == CMTime.zero {
print("INVALID DURATION")
}
} catch {
print(error.localizedDescription)
}
}
And the output for the duration in the console is:
CMTime(value: 0, timescale: 0, flags: __C.CMTimeFlags(rawValue: 17), epoch: 0)
the print(durationTest.seconds)
returns nan
, maybe that could be a clue.
Also, the url does not end in .mp3
. Maybe that could be the issue. Here is the url: https://audiopipe.suno.ai/?item_id=d5bfe2d4-0c91-4461-877b-30e9c416e10a
One possible reason is that the player may not be ready to play, but other than that I have no idea why it would be displaying a value of 0. Any ideas?