PyObjC Framework - MediaPlayer

12.1 · active · verified Tue Apr 14

This package provides Python wrappers for the macOS MediaPlayer framework, allowing Python applications to interact with system media services like accessing the user's music library and controlling playback. It is part of the larger PyObjC project, currently at version 12.1, with frequent updates tied to new macOS SDK releases and Python compatibility.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to interact with the macOS system music player using `pyobjc-framework-mediaplayer`. It attempts to find and play the first song in the user's Music library. Note that this requires macOS user permissions for 'Media & Apple Music' and actual music content in the Music.app.

import MediaPlayer
import time

# This example attempts to play a system music item.
# It requires user permission (Media & Apple Music access) and items in the Music library.
# On a system without Music.app or items, this might not do much visibly.

def play_music_item():
    player = MediaPlayer.MPMusicPlayerController.systemMusicPlayer()
    
    print(f"Initial playback state: {player.playbackState()}")

    query = MediaPlayer.MPMediaQuery.songsQuery()
    items = query.items()
    
    if items and len(items) > 0:
        first_item = items[0]
        print(f"Attempting to play: {first_item.title()} by {first_item.artist()}")
        player.setQueueWithItemCollection_(MediaPlayer.MPMediaItemCollection.collectionWithItems_([first_item]))
        player.play()
        print("Playback started. You might need to check your Music.app or system volume.")
        
        time.sleep(5) 
        player.pause()
        print("Playback paused after 5 seconds.")
    else:
        print("No music items found in the library or permissions not granted.")
        print("Please ensure Music.app has content and Python has access (System Settings > Privacy & Security > Media & Apple Music).")

if __name__ == "__main__":
    print("This script will attempt to use macOS's MediaPlayer framework.")
    print("It requires an active macOS system with the Music.app and potentially music items.")
    print("You might be prompted for Media & Apple Music access by macOS.")
    play_music_item()

view raw JSON →