avfoundationavasset

How do you actually play an AVAssetTrack, not an AVURLAsset?


Say you have a small video file

let p = Bundle.main.path(forResource: "small", ofType: "mp4")
let url = NSURL.fileURL(withPath: p!)

you can easily make it a player item and play it ..

let pi = AVPlayerItem(url: url)
av.player = AVPlayer(playerItem: pi)

Alternately, you can make it an AVURLAsset and then get one of the tracks

AVAssetTrack

 asset = AVURLAsset(url: url)
 let tracks:[AVAssetTrack] = asset!.tracks
 print(tracks.count)
 let track:AVAssetTrack = tracks[2]

How then ....... do you play one of the tracks??

how do you play an AVAssetTrack ??


Solution

  • Here is the code that shows how you can create an AVMutableComposition containing only your desired track and then play the composition as you would play any AVAsset because, perhaps surprisingly considering the name, it is one:

    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. in real life tracks and duration should probably be loaded asynchronously.