PyObjC Speech Framework

12.1 · active · verified Tue Apr 14

PyObjC-framework-Speech provides Python wrappers for the macOS Speech framework, enabling features like speech recognition. It's part of the PyObjC project, which bridges Python and Objective-C, and typically updates alongside macOS SDK releases, ensuring compatibility with the latest system features.

Warnings

Install

Imports

Quickstart

Checks the authorization status for speech recognition, requests it if not determined, and then initializes an `SFSpeechRecognizer` to check its availability and supported locales. Note that a full PyObjC application typically runs within an event loop to handle UI interactions and asynchronous callbacks properly. Running this script directly will trigger the permission dialog, but a `PyObjCTools.AppHelper.runConsoleEventLoop` might be needed for the callback to be fully processed if the script exits too quickly.

import objc
from Foundation import NSLog, NSLocale
from Speech import SFSpeechRecognizer, SFSpeechRecognizerAuthorizationStatusAuthorized, SFSpeechRecognizerAuthorizationStatusNotDetermined

def check_speech_recognizer_availability():
    # Check authorization status
    status = SFSpeechRecognizer.authorizationStatus()
    if status == SFSpeechRecognizerAuthorizationStatusNotDetermined:
        NSLog("Speech recognition authorization status: Not Determined. Requesting access...")
        # This will present a permission dialog to the user. The callback will be invoked.
        # In a full app, you'd handle the response asynchronously.
        SFSpeechRecognizer.requestAuthorization_(lambda new_status: NSLog(f"New authorization status: {new_status}"))
    elif status != SFSpeechRecognizerAuthorizationStatusAuthorized:
        NSLog(f"Speech recognition authorization denied or restricted: {status}")
        return

    # Create a recognizer for the default locale
    recognizer = SFSpeechRecognizer.alloc().init()
    if recognizer:
        NSLog(f"SFSpeechRecognizer available: {recognizer.isAvailable()}")
        NSLog(f"Supported locales: {[locale.localeIdentifier() for locale in recognizer.supportedLocales()]}")
    else:
        NSLog("Failed to create SFSpeechRecognizer. Ensure device supports speech recognition.")

if __name__ == "__main__":
    # For permission requests to fully process and callbacks to fire reliably in a script,
    # a Cocoa event loop is often necessary.
    check_speech_recognizer_availability()
    # For interactive scripts, uncomment the following lines to run a small event loop:
    # from PyObjCTools import AppHelper
    # AppHelper.runConsoleEventLoop(installInterrupt=True)

view raw JSON →