From f3126a64e750d8cd1879e331261e7ad9f60a5ba0 Mon Sep 17 00:00:00 2001 From: Alexander Eichhorn Date: Fri, 18 Oct 2024 01:08:13 +0200 Subject: [PATCH] YouTube+PlayerItem: using metadata video duration to limit playeritem video duration --- Sources/YouTubeKit/YouTube+PlayerItem.swift | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/Sources/YouTubeKit/YouTube+PlayerItem.swift b/Sources/YouTubeKit/YouTube+PlayerItem.swift index dc41125..3b31a8b 100644 --- a/Sources/YouTubeKit/YouTube+PlayerItem.swift +++ b/Sources/YouTubeKit/YouTube+PlayerItem.swift @@ -34,20 +34,26 @@ extension YouTube { return AVPlayerItem(asset: AVURLAsset(url: bestCombinedStream.url)) } } + + let videoDuration = try await metadata?.duration + let videoDurationTime = videoDuration.map { CMTime(value: CMTimeValue($0 * 1000), timescale: 1000) } // Add video track let videoAsset = AVURLAsset(url: videoStream.url) let videoTrack = composition.addMutableTrack(withMediaType: .video, preferredTrackID: kCMPersistentTrackID_Invalid) let videoAssetTrack = try await videoAsset.loadTracks(withMediaType: .video).first - let videoTimeRange = try await videoAsset.load(.duration) + let videoTimeRange = if let videoDurationTime { + videoDurationTime + } else { + try await videoAsset.load(.duration) + } try videoTrack?.insertTimeRange(CMTimeRange(start: .zero, duration: videoTimeRange), of: videoAssetTrack!, at: .zero) // Add audio track let audioAsset = AVURLAsset(url: audioStream.url) let audioTrack = composition.addMutableTrack(withMediaType: .audio, preferredTrackID: kCMPersistentTrackID_Invalid) let audioAssetTrack = try await audioAsset.load(.tracks).first { $0.mediaType == .audio } - let audioTimeRange = try await audioAsset.load(.duration) - try audioTrack?.insertTimeRange(CMTimeRange(start: .zero, duration: audioTimeRange), of: audioAssetTrack!, at: .zero) + try audioTrack?.insertTimeRange(CMTimeRange(start: .zero, duration: videoTimeRange), of: audioAssetTrack!, at: .zero) let playerItem = AVPlayerItem(asset: composition) return playerItem