我正在尝试在用户观看视频的同时录制来自前置摄像头的视频。没有音频输入,源代码就像魅力一样,但是当我激活音频输入时,视频才开始播放。这可能还是我想要实现一些不可能的事情?
录制视频源代码
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.session.beginConfiguration()
self.session.sessionPreset = AVCaptureSessionPresetMedium
// Add video input.
do {
guard let videoDevice = AVCaptureDevice.defaultDevice(withDeviceType: .builtInWideAngleCamera, mediaType: AVMediaTypeVideo, position: .front) else {fatalError()}
let videoDeviceInput = try AVCaptureDeviceInput(device: videoDevice)
if self.session.canAddInput(videoDeviceInput) {
self.session.addInput(videoDeviceInput)
} else {
print("Could not add video device input to the session")
self.session.commitConfiguration()
return
}
} catch {
print("Could not create video device input: \(error)")
self.session.commitConfiguration()
return
}
// Add audio input.
do {
guard let audioDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeAudio) else {fatalError()}
let audioDeviceInput = try AVCaptureDeviceInput(device: audioDevice)
if self.session.canAddInput(audioDeviceInput) {
self.session.addInput(audioDeviceInput)
}
else {
print("Could not add audio device input to the session")
}
} catch {
print("Could not create audio device input: \(error)")
}
self.videoPreviewLayer = AVCaptureVideoPreviewLayer(session: self.session)
self.videoPreviewLayer!.videoGravity = AVLayerVideoGravityResizeAspect
self.videoPreviewLayer!.connection?.videoOrientation = AVCaptureVideoOrientation.portrait
self.cameraElement.layer.addSublayer(self.videoPreviewLayer!)
self.session.commitConfiguration()
self.session.startRunning()
}
func startRecording() {
let recordingDelegate: AVCaptureFileOutputRecordingDelegate? = self
self.videoFileOutput = AVCaptureMovieFileOutput()
self.session.addOutput(videoFileOutput)
let filePath = NSURL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("tmpVideo.mov")
ContentController.tmpFilePath = filePath
videoFileOutput?.startRecording(toOutputFileURL: filePath, recordingDelegate: recordingDelegate)
}
播放视频源代码
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
player = AVPlayer(url: ContentController.content!.url!)
let playerLayer: AVPlayerLayer = AVPlayerLayer(player: player)
playerLayer.frame = self.videoElement.bounds
self.videoElement.layer.addSublayer(playerLayer)
player?.currentItem!.addObserver(self, forKeyPath: "status", options: NSKeyValueObservingOptions(), context: nil)
}
答案 0 :(得分:0)
问题在于线程处理。
我的解决方案是:
func playerReadyToPlay() {
DispatchQueue.global(qos: .userInitiated).async {
self.player?.play()
}
super.startRecording()
}