Skip to content

Commit

Permalink
YouTube+PlayerItem: using metadata video duration to limit playeritem…
Browse files Browse the repository at this point in the history
… video duration
  • Loading branch information
alexeichhorn committed Oct 17, 2024
1 parent 09202bd commit f3126a6
Showing 1 changed file with 9 additions and 3 deletions.
12 changes: 9 additions & 3 deletions Sources/YouTubeKit/YouTube+PlayerItem.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit f3126a6

Please sign in to comment.