我正在尝试将一个录像带和两个录像带与AVComposition结合起来。它工作正常(我有一些带有两个录音带的视频),但是有一个奇怪的问题:当我试图在播放器中播放结果视频时,它正在播放,比如18秒,之后它开始于开始!
之后就可以了。
为什么会发生?
videoAsset,audioAsset和audioAsset2只是用URL初始化的AVAssets。
//Creating AVMutableComposition
var mixComposition = AVMutableComposition()
let videoTrack = mixComposition.addMutableTrackWithMediaType(AVMediaTypeVideo, preferredTrackID: Int32(kCMPersistentTrackID_Invalid))
try! videoTrack.insertTimeRange(CMTimeRangeMake(kCMTimeZero, videoAsset.duration),
ofTrack: videoAsset.tracksWithMediaType(AVMediaTypeVideo)[0],
atTime: kCMTimeZero)
let audioTrack = mixComposition.addMutableTrackWithMediaType(AVMediaTypeAudio, preferredTrackID: 0)
try! audioTrack.insertTimeRange(CMTimeRangeMake(kCMTimeZero, CMTimeAdd(kCMTimeZero, audioAsset.duration)),ofTrack: audioAsset.tracksWithMediaType(AVMediaTypeAudio)[0], atTime: kCMTimeZero)
//the first audiotrack is very short, it's just an overlay for the first several seconds
let audioTrack2 = mixComposition.addMutableTrackWithMediaType(AVMediaTypeAudio, preferredTrackID: 1)
try! audioTrack2.insertTimeRange(CMTimeRangeMake(kCMTimeZero, videoAsset.duration), ofTrack: audioAsset2.tracksWithMediaType(AVMediaTypeAudio)[0], atTime: kCMTimeZero)
//this one is the main audiotrack for the video. its length slighly bigger than video duration, so I use videoAsset.duration here
//Player
self.videoitem = AVPlayerItem(asset: mixComposition)
player = AVPlayer(playerItem: self.videoitem)
let playerLayer = AVPlayerLayer(player: player)
playerLayer.backgroundColor = UIColor.blackColor().CGColor
playerLayer.frame = CGRectMake(0, 0, screenWidth, screenHeight)
self.view.layer.addSublayer(playerLayer)
NSNotificationCenter.defaultCenter().addObserver(self,
selector: "playerItemDidReachEnd:",
name: AVPlayerItemDidPlayToEndTimeNotification,
object: player.currentItem)
player.volume = 0.7
player.play()