Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make AVPlayer appear instantly instead of after video ends?

Our app lets users record a video, after which the app adds subtitles and exports the edited video.

The goal is to replay the video immediately, but the AVPlayer only appears after the video finishes (and only plays audio, which is a separate issue).

Here's what happens now: we show a preview so the user can see what he is recording in real-time. After the user is done recording, we want to play back the video for review. Unfortunately, no video appears, and only audio plays back. An image representing some frame of the video appears when the audio is done playing back.

Why is this happening?

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()
}
like image 651
Crashalot Avatar asked Jun 26 '15 02:06

Crashalot


2 Answers

Perhaps this can help:

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)
     }
})

Send "url" to "playPreview" leaving "completionBlock" and not that which comes from "AVAssetExportSession"

Perhaps...!

like image 114
eliasRuizHz Avatar answered Oct 23 '22 12:10

eliasRuizHz


The answer was we had an incorrectly composed video in the first place, as described here: AVAssetExportSession export fails non-deterministically with error: "Operation Stopped, NSLocalizedFailureReason=The video could not be composed.".

The other part of the question (audio playing long before images/video appears) was answered here: Long delay before seeing video when AVPlayer created in exportAsynchronouslyWithCompletionHandler

Hope these help someone avoid the suffering we endured! :)

like image 22
Crashalot Avatar answered Oct 23 '22 11:10

Crashalot