PyObjC AVKit Framework

12.1 · active · verified Tue Apr 14

PyObjC is a bridge between Python and Objective-C, enabling Python scripts to use and extend macOS Cocoa libraries. `pyobjc-framework-avkit` provides Python wrappers for Apple's AVKit framework on macOS, allowing developers to integrate video playback and related UI elements into Python applications. It is part of the larger PyObjC project, which is actively maintained with frequent updates to support new macOS SDKs and Python versions. The current version is 12.1.

Warnings

Install

Imports

Quickstart

This example demonstrates how to create a basic macOS application using PyObjC that displays and plays a video using AVKit. It sets up an `NSApplication` with an `NSWindow` and embeds an `AVPlayerViewController` to play a video from a URL. Remember that Objective-C method calls are translated to Python by replacing colons with underscores and appending an underscore for each argument.

import objc
from Foundation import NSURL
from AppKit import NSApplication, NSWindow, NSView, NSNotificationCenter, NSApplicationDidFinishLaunchingNotification, NSObject, NSRect
from AVKit import AVPlayer, AVPlayerViewController

class AppDelegate(NSObject):
    def applicationDidFinishLaunching_(self, notification):
        print("Application finished launching.")
        self.mainWindow = NSWindow.alloc().initWithContentRect_styleMask_backing_defer_(
            NSRect(100, 100, 640, 480),
            4|8|16|1, # Titled | Closable | Miniaturizable | Resizable
            2, # Backing store buffered
            False # Not deferred
        )
        self.mainWindow.setTitle_("PyObjC AVKit Demo")

        # Create an AVPlayer with a sample video URL
        video_url = NSURL.URLWithString_("https://www.learningcontainer.com/wp-content/uploads/2020/05/sample-mp4-file.mp4")
        self.player = AVPlayer.playerWithURL_(video_url)

        # Create an AVPlayerViewController
        self.playerViewController = AVPlayerViewController.alloc().init()
        self.playerViewController.setPlayer_(self.player)

        # Add the player view controller's view to the window's content view
        playerView = self.playerViewController.view()
        playerView.setFrame_(self.mainWindow.contentView().bounds())
        playerView.setAutoresizingMask_(NSView.ViewWidthSizable | NSView.ViewHeightSizable)
        self.mainWindow.contentView().addSubview_(playerView)

        self.mainWindow.makeKeyAndOrderFront_(self)
        self.player.play()

def main():
    app = NSApplication.sharedApplication()
    delegate = AppDelegate.alloc().init()
    app.setDelegate_(delegate)
    NSApplication.sharedApplication().run()

if __name__ == '__main__':
    main()

view raw JSON →