看了這個問題:AVAudioSession AVAudioSessionCategoryPlayAndRecord glitch,我試圖刺激試圖獲得視頻錄製與背景音樂播放正常工作。錄音開始時,我正在處理音頻毛刺,當錄音結束時,第一次錄音發生時工作正常。但如果我嘗試再次錄製,音樂將停止。AVCaptureSession和AVAudioSession錄製視頻,而背景音樂播放只能工作一次
任何想法爲什麼?
這裏是我的代碼片段:
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()
}
這是開始記錄代碼:
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()
,以及停止記錄:
let audioSession = AVAudioSession.sharedInstance()
try! audioSession.setCategory(AVAudioSessionCategoryAmbient, with: [.mixWithOthers, .allowAirPlay])
captureSession?.beginConfiguration()
captureSession?.removeInput(audioDeviceInput)
captureSession?.commitConfiguration()
你有可運行的代碼片段,你可以鏈接到? –
你是如何演奏音樂的?我使用了'AVAudioEngine',你的代碼可以很好地工作。 –