Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

macOS/swift Capture Audio with AVCaptureSession

I am currently trying to implement a simple audio recording tool on my Mac. Since I need the raw audio buffers in-memory, I cannot use AVAudioRecorder, which would just write the recording to a file.

My approach is to create a AVCaptureSession, Input(Microphone) and Output(AVCaptureAudioDataOutput) and start the session. Everything works fine, however the delegate callback of the output is never called.

I made sure to add mic/camera permissions (just in case) in the project settings.

Maybe someone can help me with this!

Here's my code:

import Foundation
import AVFoundation

class AudioCaptureSession: NSObject, AVCaptureAudioDataOutputSampleBufferDelegate {

    let settings = [
        AVFormatIDKey: kAudioFormatMPEG4AAC,
        AVNumberOfChannelsKey : 1,
        AVSampleRateKey : 44100]
    let captureSession = AVCaptureSession()

    override init() {
        super.init()

        let queue = DispatchQueue(label: "AudioSessionQueue", attributes: [])
        let captureDevice = AVCaptureDevice.default(for: AVMediaType.audio)
        var audioInput : AVCaptureDeviceInput? = nil
        var audioOutput : AVCaptureAudioDataOutput? = nil

        do {
            try captureDevice?.lockForConfiguration()
            audioInput = try AVCaptureDeviceInput(device: captureDevice!)
            captureDevice?.unlockForConfiguration()
            audioOutput = AVCaptureAudioDataOutput()
            audioOutput?.setSampleBufferDelegate(self, queue: queue)
            audioOutput?.audioSettings = settings
        } catch {
            print("Capture devices could not be set")
            print(error.localizedDescription)
        }

        if audioInput != nil && audioOutput != nil {
            captureSession.beginConfiguration()
            if (captureSession.canAddInput(audioInput!)) {
                captureSession.addInput(audioInput!)
            } else {
                print("cannot add input")
            }
            if (captureSession.canAddOutput(audioOutput!)) {
                captureSession.addOutput(audioOutput!)
            } else {
                print("cannot add output")
            }
            captureSession.commitConfiguration()

            print("Starting capture session")
            captureSession.startRunning()
        }
    }

    func captureOutput(_ output: AVCaptureOutput,
                       didOutput sampleBuffer: CMSampleBuffer,
                       from connection: AVCaptureConnection) {

        print("Audio data recieved")
    }
}
like image 534
David Bauer Avatar asked Apr 01 '18 13:04

David Bauer


1 Answers

It's called for me. You don't show how you use it, but maybe your AudioCaptureSession is going out of scope and being deallocated.

like image 186
Rhythmic Fistman Avatar answered Oct 20 '22 02:10

Rhythmic Fistman