After looking at this question: AVAudioSession AVAudioSessionCategoryPlayAndRecord glitch, i tried to take a stab at trying to get video recording with background music playing working correctly. I'm settling for the audio glitch when recording starts, and when it ends, and it works fine the first time the recording happens. But if I try to record again, the music will stop.
Any ideas why?
Here's a snippet of my code:
captureSession = AVCaptureSession()
captureSession?.automaticallyConfiguresApplicationAudioSession = false
captureSession?.usesApplicationAudioSession = true
guard let captureSession = self.captureSession else {
print("Error making capture session")
return;
}
captureSession.sessionPreset = AVCaptureSessionPresetHigh
self.camera = self.defaultBackCamera()
self.audioDeviceInput = try? AVCaptureDeviceInput(device: getAudioDevice())
cameraInput = try AVCaptureDeviceInput(device: camera)
captureSession.beginConfiguration()
if captureSession.inputs.count > 0 {
return
}
if captureSession.canAddInput(cameraInput) {
captureSession.addInput(cameraInput)
if captureSession.outputs.count == 0 {
photoOutput = AVCapturePhotoOutput()
if captureSession.canAddOutput(photoOutput!) {
captureSession.addOutput(self.photoOutput!)
}
}
captureSession.commitConfiguration()
if !captureSession.isRunning {
captureSession.startRunning()
self.previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
self.previewLayer!.videoGravity = AVLayerVideoGravityResizeAspect
self.previewLayer!.connection.videoOrientation = .portrait
self.previewLayer!.frame = cameraView.layer.bounds
self.cameraView.layer.addSublayer(self.previewLayer!)
captureSession.beginConfiguration()
videoFileOut = AVCaptureMovieFileOutput()
if (captureSession.canAddOutput(videoFileOut)) {
captureSession.addOutput(videoFileOut)
if (videoFileOut?.connection(withMediaType: AVMediaTypeVideo).isVideoStabilizationSupported)! {
videoFileOut?.connection(withMediaType: AVMediaTypeVideo).preferredVideoStabilizationMode = .cinematic
}
}
captureSession.commitConfiguration()
}
This is the code to start recording:
let audioSession = AVAudioSession.sharedInstance()
try! audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord,
with: [.mixWithOthers, .allowBluetoothA2DP, .allowAirPlay])
try! audioSession.setActive(true)
captureSession?.beginConfiguration()
if (captureSession?.canAddInput(audioDeviceInput!))! {
captureSession?.addInput(audioDeviceInput!)
}
captureSession?.commitConfiguration()
And to stop recording:
let audioSession = AVAudioSession.sharedInstance()
try! audioSession.setCategory(AVAudioSessionCategoryAmbient, with: [.mixWithOthers, .allowAirPlay])
captureSession?.beginConfiguration()
captureSession?.removeInput(audioDeviceInput)
captureSession?.commitConfiguration()