Reputation: 156
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:
- Custom camera opened;
- I've recorded a video;
- Controller with recorded video preview is shown. (by pushViewController(controller, animated: true));
- Video started playing;
- After N seconds (1-2 sec) video stopped for some reason.
The code:
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.
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()
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
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