Skip to content

Instantly share code, notes, and snippets.

@timsutton
Created March 16, 2016 18:48
Show Gist options
  • Select an option

  • Save timsutton/0c6439eb6eb1621a5964 to your computer and use it in GitHub Desktop.

Select an option

Save timsutton/0c6439eb6eb1621a5964 to your computer and use it in GitHub Desktop.
Screen recording with Python and AVFoundation
#!/usr/bin/python
# pylint: disable-msg=e1101,e0611
import time
import AVFoundation as AVF
import Quartz
from Foundation import NSObject, NSURL
def main():
display_id = Quartz.CGMainDisplayID()
session = AVF.AVCaptureSession.alloc().init()
screen_input = AVF.AVCaptureScreenInput.alloc().initWithDisplayID_(display_id)
file_output = AVF.AVCaptureMovieFileOutput.alloc().init()
session.addInput_(screen_input)
session.addOutput_(file_output)
session.startRunning()
file_url = NSURL.fileURLWithPath_('foo.mov')
# Cheat and pass a dummy delegate object where normally we'd have a
# AVCaptureFileOutputRecordingDelegate
file_url = file_output.startRecordingToOutputFileURL_recordingDelegate_(
file_url, NSObject.alloc().init())
time.sleep(10)
session.stopRunning()
if __name__ == '__main__':
main()
@0dm

0dm commented Jun 30, 2023

Copy link
Copy Markdown

hi,

is it possible to get audio too? i'm pretty new to this API and have been stuck.

sorry for bothering, I see it is an old gist..

I've added this:

    # Audio Input
    audio_device = AVF.AVCaptureDevice.defaultDeviceWithMediaType_(AVF.AVMediaTypeAudio)
    audio_input = AVF.AVCaptureDeviceInput.alloc().initWithDevice_error_(audio_device, None)

    session.addInput_(audio_input)

but I get this:

    session.addInput_(audio_input)
ValueError: NSInvalidArgumentException - -[OC_BuiltinPythonArray session]: unrecognized selector sent to instance 0x60000360a150

@0dm

0dm commented Jul 7, 2023

Copy link
Copy Markdown

update: got it working :D

    objc.options.structs_indexable = True

    audio_input = AVF.AVCaptureDeviceInput.alloc().initWithDevice_error_(
        AVF.AVCaptureDevice.defaultDeviceWithMediaType_(AVF.AVMediaTypeAudio), None
    )

    if session.canAddInput_(audio_input[0]):
        session.addInput_(audio_input[0])

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment