Rodion Kuskov
Rodion Kuskov

Reputation: 156

AVPlayer video from temporary directory after recording stops playing after few seconds

I have a custom camera, which can record videos and take photos. The problem is after recording and pushing viewController with recorded video preview, video stops playing after few seconds. So the flow is:

  1. Custom camera opened;
  2. I've recorded a video;
  3. Controller with recorded video preview is shown. (by pushViewController(controller, animated: true));
  4. Video started playing;
  5. After N seconds (1-2 sec) video stopped for some reason.

The code:

  1. didFinishRecordingTo outputFileURL:
        if let error = error {
            // handle error
            return
        }

        if let currentBackgroundRecordingID = backgroundRecordingID {
            backgroundRecordingID = UIBackgroundTaskIdentifier.invalid

            if currentBackgroundRecordingID != UIBackgroundTaskIdentifier.invalid {
                UIApplication.shared.endBackgroundTask(currentBackgroundRecordingID)
            }
        } 
       // open viewController and play recently recorded video from temporary files.
  1. setupVideoBackground() -> Configuration for AVPlayer, called in viewDidLoad/viewWillAppear:
        let player = AVPlayer(url: url)
        player.actionAtItemEnd = .none

        let playerLayer = AVPlayerLayer(player: player)
        playerLayer.frame = self.view.frame
        playerLayer.videoGravity = .resizeAspectFill

        self.view.layer.insertSublayer(playerLayer, at: 0)

        player.seek(to: .zero)
        player.play()
  1. Pushing view controller:
        let vc = TestController()
        vc.url = url!
        self.navigationController?.pushViewController(vc, animated: true)   

Note: One weird thing, that if I use pushViewController with animated: false, then player will be playing full video and if with animated: true, video will be stopped after few seconds. Also, present view controller works perfectly.

Note 2: If I call setupVideoBackground() with 0.5 seconds delay by using DispatchQueue, video won't stops.

I don't understand, why video is playing correctly after pushViewController(vc, animated: false) and stops playing after pushViewController(vc, animated: true)

Upvotes: 3

Views: 580

Answers (1)

Rodion Kuskov
Rodion Kuskov

Reputation: 156

Solution 1: So the problem was in viewDidDissapear on the camera screen. There was a cameraSession.stopSession(). Each time stopSession was called, avplayer stops playing. I don't know why and how AVCaptureSession.stopSession() is related to AVPlayer, but removing cameraSession.stopSession() from viewDidDissapear fixed the problem.

Solution 2: You can set AVAudioSession category to .playAndRecord and video will plays correctly:

try AVAudioSession.sharedInstance().setCategory(.playAndRecord, mode: .videoRecording, options: [.mixWithOthers])

Upvotes: 2

Related Questions