我正在开发Apple TV应用程序。我有一个Video的URL和一个视频Subtitle的URL。 我想用副标题播放视频。任何人都有解决这个问题的方法
如果你有,请告诉我。
有一个视频网址:" https://sample/hls_playlist.m3u8"
有一个字幕网址:" https://samplesubtitle=AKIAJS5BLYTDP3J5UOFQ&Expires=1507918258&Signature=r%2FcV7UVSejOBYDKFHwMYtrvXUmM%3D"
这是我的代码:
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)
}