Search code examples
swiftmacosavcapturesession

How to record my Mac's internal sound, not the microphone!, using AVCaptureSession?


I am trying to implement a simple macOS app with screen recording capabilities.

I don't want to record a microphone input, but rather a sound that comes out of my Mac's speakers. Example: this way I want to be able to record a YouTube video to a file.

Is this possible with AVCaptureSession? Googling shows the examples that capture video and microphore, but not the internal audio.

Here is the working code that I have to capture video and microphone. What do I have to modify to disable the microphone and get the internal PC's sound that comes to the speakers?

session = AVCaptureSession()
session.sessionPreset = AVCaptureSession.Preset.high

movieFileOutput = AVCaptureMovieFileOutput()

let displayId: CGDirectDisplayID = CGDirectDisplayID(CGMainDisplayID())

let audioDevice = AVCaptureDevice.default(for: .audio)!

let audioInput = try! AVCaptureDeviceInput(device: audioDevice)

let videoInput: AVCaptureScreenInput = AVCaptureScreenInput(displayID: displayId)!

session.addInput(videoInput)
session.addInput(audioInput)
session.addOutput(movieFileOutput)

session.startRunning()
movieFileOutput.startRecording(to: self.destinationUrl, recordingDelegate: self)

Solution

  • I have not found an easy way to do it but it turns out that it is possible to make the original code record the audio given that there is another software installed on my machine: Soundflower.

    Soundflower is an open source kernel extension for MacOS, designed to create a virtual audio output device that can also act as an input.

    Given that the Soundflower is installed, one can use configure the macOS using the Applications / Utilities / Audio MIDI Setup app to send the audio to both virtual and real audio devices. This way the code above captures the audio from the Soundflower but you can still hear it on your normal audio output device.

    The setup of the Applications / Utilities / Audio MIDI Setup application is described here: How can I send my computer's audio to multiple outputs?.