你如何实际播放 AVAssetTrack,而不是 AVURLAsset?
How do you actually play an AVAssetTrack, not an AVURLAsset?
假设您有一个小视频文件
let p = Bundle.main.path(forResource: "small", ofType: "mp4")
let url = NSURL.fileURL(withPath: p!)
您可以轻松地将其设为播放器物品并播放它..
let pi = AVPlayerItem(url: url)
av.player = AVPlayer(playerItem: pi)
或者,您可以将其设为 AVURLAsset,然后获取其中一首曲目
AVAssetTrack
asset = AVURLAsset(url: url)
let tracks:[AVAssetTrack] = asset!.tracks
print(tracks.count)
let track:AVAssetTrack = tracks[2]
那么.......你会播放其中一首曲目吗??
你是怎么玩AVAssetTrack的??
这里的代码展示了如何创建一个只包含您想要的曲目的 AVMutableComposition
,然后像播放任何 AVAsset
一样播放乐曲,因为考虑到这个名称,可能令人惊讶,它是一个:
let asset = AVURLAsset(url: url)
let track = asset.tracks[1] // or whatever
let composition = AVMutableComposition()
let compositionTrack = composition.addMutableTrack(withMediaType: track.mediaType, preferredTrackID: kCMPersistentTrackID_Invalid)
try! compositionTrack?.insertTimeRange(CMTimeRange(start: .zero, duration: asset.duration), of: track, at: .zero)
let playerItem = AVPlayerItem(asset: composition) // play me in your AVPlayer
N.B. 在现实生活中 tracks
和 duration
应该是异步加载的。
假设您有一个小视频文件
let p = Bundle.main.path(forResource: "small", ofType: "mp4")
let url = NSURL.fileURL(withPath: p!)
您可以轻松地将其设为播放器物品并播放它..
let pi = AVPlayerItem(url: url)
av.player = AVPlayer(playerItem: pi)
或者,您可以将其设为 AVURLAsset,然后获取其中一首曲目
AVAssetTrack
asset = AVURLAsset(url: url)
let tracks:[AVAssetTrack] = asset!.tracks
print(tracks.count)
let track:AVAssetTrack = tracks[2]
那么.......你会播放其中一首曲目吗??
你是怎么玩AVAssetTrack的??
这里的代码展示了如何创建一个只包含您想要的曲目的 AVMutableComposition
,然后像播放任何 AVAsset
一样播放乐曲,因为考虑到这个名称,可能令人惊讶,它是一个:
let asset = AVURLAsset(url: url)
let track = asset.tracks[1] // or whatever
let composition = AVMutableComposition()
let compositionTrack = composition.addMutableTrack(withMediaType: track.mediaType, preferredTrackID: kCMPersistentTrackID_Invalid)
try! compositionTrack?.insertTimeRange(CMTimeRange(start: .zero, duration: asset.duration), of: track, at: .zero)
let playerItem = AVPlayerItem(asset: composition) // play me in your AVPlayer
N.B. 在现实生活中 tracks
和 duration
应该是异步加载的。