I am working on Apple TV application. I have one URL of Video and one URL of video Subtitle. I want to play video with subtitle. Anybody have a solution for this problem
If you have please let me know.
There is a Video URL: "https://sample/hls_playlist.m3u8"
There is a Subtitle URL: "https://samplesubtitle=AKIAJS5BLYTDP3J5UOFQ&Expires=1507918258&Signature=r%2FcV7UVSejOBYDKFHwMYtrvXUmM%3D"
This is my code:
func playVideo(_ videoURL: String) {
// 1 - Load video asset
let videoAsset = AVURLAsset.init(url: URL(string:videoURL)!) as AVURLAsset
// 2 - Create AVMutableComposition object. This object will hold your AVMutableCompositionTrack instances.
let mixComposition = AVMutableComposition.init()
// 3 - Video track
let videoTrack: AVMutableCompositionTrack? = mixComposition.addMutableTrack(withMediaType: AVMediaTypeVideo, preferredTrackID: kCMPersistentTrackID_Invalid)
try? videoTrack?.insertTimeRange(CMTimeRangeMake(kCMTimeZero, videoAsset.duration), of: (videoAsset.tracks(withMediaType: AVMediaTypeVideo)[0]), at: kCMTimeZero)
// 4 - Subtitle track
let subtitleAsset = AVURLAsset.init(url: URL(string: self.subtitle!)!)
let subtitleTrack: AVMutableCompositionTrack? = mixComposition.addMutableTrack(withMediaType: AVMediaTypeText, preferredTrackID: kCMPersistentTrackID_Invalid)
try? subtitleTrack?.insertTimeRange(CMTimeRangeMake(kCMTimeZero, videoAsset.duration), of: subtitleAsset.tracks(withMediaType: AVMediaTypeText)[0], at: kCMTimeZero)
self.playerItem = AVPlayerItem.init(asset: mixComposition)
self.playerObj = AVPlayer.init(playerItem: self.playerItem)
self.playerController?.player = self.playerObj
self.playerItem.addObserver(self, forKeyPath: Notification.Name.status.rawValue, options: NSKeyValueObservingOptions.new, context: nil)
self.playerController?.player!.play()
NotificationCenter.default.addObserver(self, selector: #selector(PlayerViewController.playerItemDidReachEnd(_:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: self.playerObj.currentItem)
}