Swift iOS Records Video and Audio with AVFoundation

I was able to successfully capture the recorded video by completing this question here

Basically

  • Inherit AVCaptureFileOutputRecordingDelegate prototype
  • Scrolling through available devices
  • Create a camera session
  • Start recording
  • Stop recording
  • Get a video by implementing the above prototype

But the file does not come with audio.

In accordance with this question, I have to record audio separately and combine video and audio using the specified classes

But I do not know how to implement video and audio recording at the same time.

 for device in devices { // Make sure this particular device supports video if (device.hasMediaType(AVMediaTypeVideo)) { // Finally check the position and confirm we've got the back camera if(device.position == AVCaptureDevicePosition.Back) { captureDevice = device as? AVCaptureDevice if captureDevice != nil { print("Capture device found") beginSession() } } } } 

only available device types are available in this cycle: .Front and .Back

0
source share
4 answers

Found an answer, This answer comes with this code

It can just be done

  • declare another capture device variable
  • connect devices and initialize the camera variable and audio capture.
  • add audio input to the session

the code

 var captureDevice : AVCaptureDevice? var captureAudio :AVCaptureDevice? 

Loop devices and capture device initialization

 var captureDeviceVideoFound: Bool = false var captureDeviceAudioFound:Bool = false // Loop through all the capture devices on this phone for device in devices { // Make sure this particular device supports video if (device.hasMediaType(AVMediaTypeVideo)) { // Finally check the position and confirm we've got the front camera if(device.position == AVCaptureDevicePosition.Front) { captureDevice = device as? AVCaptureDevice //initialize video if captureDevice != nil { print("Capture device found") captureDeviceVideoFound = true; } } } if(device.hasMediaType(AVMediaTypeAudio)){ print("Capture device audio init") captureAudio = device as? AVCaptureDevice //initialize audio captureDeviceAudioFound = true } } if(captureDeviceAudioFound && captureDeviceVideoFound){ beginSession() } 

Inside the session

 try captureSession.addInput(AVCaptureDeviceInput(device: captureDevice)) try captureSession.addInput(AVCaptureDeviceInput(device: captureAudio)) 

This will output a video file with sound. no need to combine audio or do anything.

This Apple documentation helps

+3
source

I also had this problem, but when I grouped the addition of video input and sound, after that the sound worked. This is my code for adding inputs.

  if (cameraSession.canAddInput(deviceInput) == true && cameraSession.canAddInput(audioDeviceInput) == true) {//detects if devices can be added cameraSession.addInput(deviceInput)//adds video cameraSession.addInput(audioDeviceInput)//adds audio } 

I also found that you must first have a video input, otherwise there will be no sound. I initially had them in two if operations, but I found that they fit in the same color, and video and audio are recorded together. Hope this helps.

0
source

The following is a way to record video with sound using the AVFoundation framework. Steps:

1. Prepare the session:

  self.captureSession = AVCaptureSession() 

2. Prepare available video and audio devices:

  let session = AVCaptureDevice.DiscoverySession.init(deviceTypes:[.builtInWideAngleCamera, .builtInMicrophone], mediaType: AVMediaType.video, position: AVCaptureDevice.Position.unspecified) let cameras = (session.devices.compactMap{$0}) for camera in cameras { if camera.position == .front { self.frontCamera = camera } if camera.position == .back { self.rearCamera = camera try camera.lockForConfiguration() camera.focusMode = .continuousAutoFocus camera.unlockForConfiguration() } } // Add audio device self.audioDevice = AVCaptureDevice.default(for: AVMediaType.audio) 

3. Prepare the session input:

  guard let captureSession = self.captureSession else { throw CameraControllerError.captureSessionIsMissing } if let rearCamera = self.rearCamera { self.rearCameraInput = try AVCaptureDeviceInput(device: rearCamera) if captureSession.canAddInput(self.rearCameraInput!) { captureSession.addInput(self.rearCameraInput!) self.currentCameraPosition = .rear } else { throw CameraControllerError.inputsAreInvalid } } else if let frontCamera = self.frontCamera { self.frontCameraInput = try AVCaptureDeviceInput(device: frontCamera) if captureSession.canAddInput(self.frontCameraInput!) { captureSession.addInput(self.frontCameraInput!) self.currentCameraPosition = .front } else { throw CameraControllerError.inputsAreInvalid } } else { throw CameraControllerError.noCamerasAvailable } // Add audio input if let audioDevice = self.audioDevice { self.audioInput = try AVCaptureDeviceInput(device: audioDevice) if captureSession.canAddInput(self.audioInput!) { captureSession.addInput(self.audioInput!) } else { throw CameraControllerError.inputsAreInvalid } } 

4. Prepare a conclusion:

  self.videoOutput = AVCaptureMovieFileOutput() if captureSession.canAddOutput(self.videoOutput!) { captureSession.addOutput(self.videoOutput!) } captureSession.startRunning() 

5. Start recording:

  func recordVideo(completion: @escaping (URL?, Error?)-> Void) { guard let captureSession = self.captureSession, captureSession.isRunning else { completion(nil, CameraControllerError.captureSessionIsMissing) return } let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) let fileUrl = paths[0].appendingPathComponent("output.mp4") try? FileManager.default.removeItem(at: fileUrl) videoOutput!.startRecording(to: fileUrl, recordingDelegate: self) self.videoRecordCompletionBlock = completion } 

6. Stop recording:

  func stopRecording(completion: @escaping (Error?)->Void) { guard let captureSession = self.captureSession, captureSession.isRunning else { completion(CameraControllerError.captureSessionIsMissing) return } self.videoOutput?.stopRecording() } 

7. Implement the delegate:

  func fileOutput(_ output: AVCaptureFileOutput, didFinishRecordingTo outputFileURL: URL, from connections: [AVCaptureConnection], error: Error?) { if error == nil { //do something } else { //do something } } 

I took the idea from here: https://www.appcoda.com/avfoundation-swift-guide/

Here is the complete project https://github.com/rubaiyat6370/iOS-Tutorial/

0
source

Record video from audio

 //Get Video Device if let devices = AVCaptureDevice.devices(withMediaType: AVMediaTypeVideo) as? [AVCaptureDevice] { for device in devices { if device.hasMediaType(AVMediaTypeVideo) { if device .position == AVCaptureDevicePosition.back{ videoCaptureDevice = device } } } if videoCaptureDevice != nil { do { // Add Video Input try self.captureSession.addInput(AVCaptureDeviceInput(device: videoCaptureDevice)) // Get Audio Device let audioInput = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeAudio) //Add Audio Input try self.captureSession.addInput(AVCaptureDeviceInput(device: audioInput)) self.previewLayer = AVCaptureVideoPreviewLayer(session: self.captureSession) previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill previewLayer.connection.videoOrientation = AVCaptureVideoOrientation.portrait self.videoView.layer.addSublayer(self.previewLayer) //Add File Output self.captureSession.addOutput(self.movieOutput) captureSession.startRunning() }catch { print(error) } 

For more details see the link:

https://medium.com/@santhosh3386/ios-avcapturesession-record-video-with-audio-23c8f8c9a8f8

-one
source

Source: https://habr.com/ru/post/1014022/


All Articles