2017-04-19 105 views
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視頻中。

回答

0

我的應用程序中的代碼與您的應用程序幾乎完全相同,它適用於Airplay模式,因此我認爲您幾乎可以在那裏使用。

我從網絡服務器加載視頻,音頻和VTT-字幕,有兩個主要挑戰:

  1. 音頻無法播放,除非它從https主機無論plist中的設置來(視頻精打從基於HTTP主機)
  2. 字幕只能播放10-12分鐘的電影。解決辦法是使用文件管理器

從您的代碼唯一的區別是,我初始化AVPlayerViewController從.documentDirectory下載字幕和負載,並設置玩家的AVPlayer:

var moviePlayer = AVPlayerViewController() 
moviePlayer.player = player 

,然後呈現moviePlayer

self.view.window?.rootViewController?.present(self.moviePlayer, animated: true, completion : { self.moviePlayerFinishedLoading() } 
self.moviePlayer.player?.play() 

希望這有助於

相關問題