如何使AVPlayer立即显示而不是在视频结束后?

时间:2015-06-26 02:12:18

标签: ios swift video avfoundation avplayer

我们的应用可让用户录制视频,之后应用会添加字幕并导出已编辑的视频。

目标是立即重播视频,但AVPlayer仅在视频播放完毕后出现(并且只播放音频,这是一个单独的问题)。

现在发生了什么:我们展示预览,以便用户可以实时查看他正在录制的内容。用户完成录制后,我们要播放视频以供审核。不幸的是,没有视频出现,只播放音频。当音频完成播放时,会出现代表视频某帧的图像。

为什么会这样?

func exportDidFinish(exporter: AVAssetExportSession) {
    println("Finished exporting video")

    // Save video to photo album
    let assetLibrary = ALAssetsLibrary()
    assetLibrary.writeVideoAtPathToSavedPhotosAlbum(exporter.outputURL, completionBlock: {(url: NSURL!, error: NSError!) in
        println("Saved video to album \(exporter.outputURL)")
        self.playPreview(exporter.outputURL)
        if (error != nil) {
            println("Error saving video")
        }
    })
}


func playPreview(videoUrl: NSURL) {
    let asset = AVAsset.assetWithURL(videoUrl) as? AVAsset
    let playerItem = AVPlayerItem(asset: asset)
    player = AVPlayer(playerItem: playerItem)
    let playerLayer = AVPlayerLayer(player: player)
    playerLayer.frame = view.frame
    view.layer.addSublayer(playerLayer)
    player.play()
}

2 个答案:

答案 0 :(得分:3)

也许这会有所帮助:

let assetLibrary = ALAssetsLibrary()
assetLibrary.writeVideoAtPathToSavedPhotosAlbum(exporter.outputURL, completionBlock: {(url: NSURL!, error: NSError!) in
     if (error != nil) {
       println("Error saving video")
     }else{
       println("Saved video to album \(url)")
       self.playPreview(url)
     }
})

发送" url"到" playPreview"离开" completionBlock"而不是来自" AVAssetExportSession"

也许......!

答案 1 :(得分:2)

答案是我们首先制作了错误合成的视频,如下所述:AVAssetExportSession export fails non-deterministically with error: "Operation Stopped, NSLocalizedFailureReason=The video could not be composed."

问题的另一部分(在图像/视频出现之前很久播放的音频)在这里得到了解答:Long delay before seeing video when AVPlayer created in exportAsynchronouslyWithCompletionHandler

希望这些可以帮助别人避免我们忍受的痛苦! :)