Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@hashaam
Created August 1, 2022 20:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hashaam/56b25d843610a5162f01ff2b5beb35c2 to your computer and use it in GitHub Desktop.
Save hashaam/56b25d843610a5162f01ff2b5beb35c2 to your computer and use it in GitHub Desktop.
Capture Microphone Sound
/*
Step 1 - Privacy Text for Requesting Microphone Permission
Open the Info.plist file as source code and enter the following text in the <dict></dict>:
<key>NSMicrophoneUsageDescription</key>
<string>This app requires microphone</string>
*/
/*
Step 2 - Imports
*/
import AVFoundation
/*
Step 3 - Check for Microphone Permission
*/
let status = AVCaptureDevice.authorizationStatus(for: .audio)
switch status {
case .authorized: print("authorized")
case .notDetermined: print("permission not requested")
default: print("other unknown cases")
}
/*
Step 4 - Request for Microphone Permission
*/
AVCaptureDevice.requestAccess(for: .audio) { granted in
DispatchQueue.main.async {
guard granted else {
print("permission not granted")
return
}
print("authorized")
}
}
/*
Step 5 - Get Microphone Capture Device
*/
func getMicrophoneCaptureDevice() -> AVCaptureDevice? {
if let microphoneCaptureDevice = AVCaptureDevice.default(.builtInMicrophone, for: .audio, position: .unspecified) {
return microphoneCaptureDevice
}
return nil
}
/*
Step 6 - Get Microphone Capture Device Input
*/
func getCaptureDeviceInput(captureDevice: AVCaptureDevice) -> AVCaptureDeviceInput? {
do {
let captureDeviceInput = try AVCaptureDeviceInput(device: captureDevice)
return captureDeviceInput
} catch let error {
print("Failed to get capture device input with error \(error)")
}
return nil
}
/*
Step 7 - Add Microphone Capture Device Input to Capture Session Controller
*/
let captureSession: AVCaptureSession
if let audioCaptureDevice = getMicrophoneCaptureDevice() {
if let audioCaptureDeviceInput = getCaptureDeviceInput(captureDevice: audioCaptureDevice) {
if captureSession.canAddInput(audioCaptureDeviceInput) {
captureSession.addInput(audioCaptureDeviceInput)
}
}
}
/*
Step 8 - Remove Microphone Capture Device Input
*/
captureSession.removeInput(audioCaptureDeviceInput)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment