PyObjC Framework - MediaPlayer
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
- breaking PyObjC 12.0 dropped support for Python 3.9. Ensure your environment uses Python 3.10 or newer.
- breaking PyObjC 11.1 changed how initializer methods are handled, aligning with clang's Automatic Reference Counting (ARC) documentation. Methods in the 'init' family now correctly 'steal' a reference to self and return a new one. This can affect memory management and object lifecycles if your code relied on the previous behavior.
- gotcha PyObjC 10.3 introduced a change preventing `__init__` from being called when a user-implemented `__new__` was present in a class or its superclasses. This was partially reverted in 10.3.1 to re-enable `__init__` use when a user implements `__new__`, but still prohibits it when relying on PyObjC's provided `__new__`.
- gotcha The MediaPlayer framework on macOS requires specific user permissions (e.g., 'Media & Apple Music' access in System Settings > Privacy & Security). Your application might need to handle cases where these permissions are not granted, which can lead to silent failures or permission prompts.
Install
-
pip install pyobjc-framework-mediaplayer
Imports
- MediaPlayer
import MediaPlayer
Quickstart
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()