user1569766
user1569766

Reputation: 25

How can I capture audio samples output on macOS?

I'm trying to capture audio samples from the selected output device on macOS. I attempted to use AVAudioEngine with installTap, but I haven't had any success.

Here's a snippet of what I've tried so far:

class AudioOutputCaptureManager {
private let audioEngine = AVAudioEngine()
private var captureCallback: (([Float]) -> Void)?

init() {
    setupAudioEngine()
}

private func setupAudioEngine() {
    let inputNode = audioEngine.inputNode
    let inputFormat = inputNode.inputFormat(forBus: 0)
    
    inputNode.installTap(onBus: 0, bufferSize: 1024, format: inputFormat) { buffer, _ in
        let frameLength = Int(buffer.frameLength)
        let channels = UnsafeBufferPointer(start: buffer.floatChannelData, count: Int(buffer.format.channelCount))
        
        if let channelData = channels.first {
            let samples = Array(UnsafeBufferPointer(start: channelData, count: frameLength))
            self.captureCallback?(samples)
        }
    }
}

func startCapturing(callback: @escaping ([Float]) -> Void) {
    self.captureCallback = callback
    do {
        try audioEngine.start()
    } catch {
        print("Failed to start AVAudioEngine: \(error)")
    }
}

func stopCapturing() {
    
}

}

Upvotes: 0

Views: 79

Answers (0)

Related Questions