Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ??

like image 719
Fattie Avatar asked Oct 27 '25 07:10

Fattie


1 Answers

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.

like image 187
Rhythmic Fistman Avatar answered Oct 29 '25 09:10

Rhythmic Fistman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!