1
我的代碼如下:如何在使用AVComposition時避免Airplay凍結?
//init mix composition
let mixComposition = AVMutableComposition()
//video asset
let videoAsset = AVURLAsset(url: VIDEO_URL)
let videoTrack = mixComposition.addMutableTrack(withMediaType: AVMediaTypeVideo, preferredTrackID: kCMPersistentTrackID_Invalid)
try? videoTrack.insertTimeRange(CMTimeRangeMake(kCMTimeZero, videoAsset.duration), of: videoAsset.tracks(withMediaType: AVMediaTypeVideo).first!, at: kCMTimeZero)
//audio track
let audioTrack = mixComposition.addMutableTrack(withMediaType: AVMediaTypeAudio, preferredTrackID: kCMPersistentTrackID_Invalid)
try? audioTrack.insertTimeRange(CMTimeRangeMake(kCMTimeZero, videoAsset.duration), of: videoAsset.tracks(withMediaType: AVMediaTypeAudio).first!, at: kCMTimeZero)
//subtitles
let path = Bundle.main.path(forResource: "subtitle", ofType: "vtt")!
let subtitleAsset = AVAsset(url: URL(fileURLWithPath: path))
let subtitleTrack = mixComposition.addMutableTrack(withMediaType: AVMediaTypeText, preferredTrackID: kCMPersistentTrackID_Invalid)
try? subtitleTrack.insertTimeRange(CMTimeRangeMake(kCMTimeZero, videoAsset.duration), of: subtitleAsset.tracks(withMediaType: AVMediaTypeText)[0], at: kCMTimeZero)
//setup player and play
let item = AVPlayerItem(asset: videoAsset)
let player = AVPlayer(playerItem: item)
self.player = player
self.player?.allowsExternalPlayback = true
self.player?.usesExternalPlaybackWhileExternalScreenIsActive = true
self.player?.play()
當被問到videoAsset.isCompatibleWithAirPlayVideo
返回true。當您加載應用程序時,它會一直運行,直到您進入Airplay模式,屏幕將凍結,直到您再次退出Airplay模式。
如果您要將mixComposition更改爲videoAsset,則這是完全不同的行爲。現在一切正常,但你不會有外部字幕。
還有其他人遇到過這個問題和解決方法。我的最終目標是將外部字幕包含到mp4視頻中。