A python interface to the mpv media player
npx @tessl/cli install tessl/pypi-mpv@1.0.0A comprehensive Python interface to the mpv media player through ctypes bindings to libmpv. Provides complete control over mpv's features similar to the Lua interface, enabling developers to embed video and audio playback capabilities into Python applications.
pip install mpvimport mpvMost commonly used:
from mpv import MPVFor specific components:
from mpv import MPV, ErrorCode, MpvFormat, MpvEventIDimport mpv
import time
# Create mpv player instance
player = mpv.MPV()
# Play a video file
player.play('/path/to/video.mp4')
# Wait for playback to start
player.wait_until_playing()
# Control playback
player.pause = True
time.sleep(2)
player.pause = False
# Seek to 30 seconds
player.seek(30, reference='absolute')
# Access properties
print(f"Duration: {player.duration}")
print(f"Position: {player.time_pos}")
print(f"Volume: {player.volume}")
# Set properties
player.volume = 50
player.fullscreen = True
# Observe property changes
@player.property_observer('time-pos')
def time_observer(name, value):
print(f"Current position: {value}")
# Register event callback
@player.event_callback('end-file')
def end_file_handler(event):
print("Playback finished")
# Wait for playback to complete
player.wait_for_playback()
# Clean up
player.terminate()The python-mpv library provides multiple layers of abstraction:
The library maintains compatibility with mpv's property system and command interface, ensuring feature parity with mpv's native capabilities.
Essential playback functionality including play, pause, seek, stop operations, and basic player lifecycle management.
class MPV:
def play(self, filename: str): ...
def seek(self, amount: float, reference: str = "relative", precision: str = "keyframes"): ...
def stop(self, keep_playlist: bool = False): ...
def terminate(self): ...
# Properties
pause: bool
time_pos: float
duration: float
```
[Core Playback](./core-playback.md)
### Property Management
Complete access to mpv's property system with observation capabilities, type conversion, and specialized property accessors.
```python { .api }
class MPV:
def observe_property(self, name: str, handler): ...
def property_observer(self, name: str): ... # decorator
def unobserve_property(self, name: str, handler): ...
# Property access
def __getattr__(self, name): ...
def __setattr__(self, name, value): ...
properties: dict
osd: PropertyProxy
file_local: PropertyProxyComprehensive event system for monitoring player state, handling errors, and responding to user interactions.
class MPV:
def register_event_callback(self, callback): ...
def event_callback(self, *event_types): ... # decorator
def wait_for_event(self, *event_types, **kwargs): ...
# Event classes
class MpvEvent: ...
class MpvEventProperty: ...
class MpvEventLogMessage: ...
class MpvEventEndFile: ...Playlist management, file loading with options, and track selection for audio, video, and subtitle tracks.
class MPV:
def loadfile(self, filename: str, mode: str = 'replace', **options): ...
def loadlist(self, playlist: str, mode: str = 'replace'): ...
def playlist_append(self, filename: str, **options): ...
def playlist_next(self, mode: str = 'weak'): ...
def playlist_prev(self, mode: str = 'weak'): ...
def audio_add(self, url: str, flags: str = 'select', **kwargs): ...
def video_add(self, url: str, flags: str = 'select', **kwargs): ...
def sub_add(self, url: str, flags: str = 'select', **kwargs): ...Screenshot capture with multiple output formats and overlay system for images and text on top of video content.
class MPV:
def screenshot(self, includes: str = 'subtitles', mode: str = 'single'): ...
def screenshot_to_file(self, filename: str, includes: str = 'subtitles'): ...
def screenshot_raw(self, includes: str = 'subtitles'): ...
def create_image_overlay(self, img=None, pos=(0,0)): ...
def create_file_overlay(self, filename=None, **kwargs): ...
class ImageOverlay: ...
class FileOverlay: ...Input event handling, custom key bindings, mouse interaction, and OSD (On-Screen Display) control.
class MPV:
def keypress(self, name: str): ...
def keybind(self, name: str, command: str): ...
def register_key_binding(self, keydef: str, callback_or_cmd, mode: str = 'force'): ...
def key_binding(self, keydef: str, mode: str = 'force'): ... # decorator
def mouse(self, x: int, y: int, button=None, mode: str = 'single'): ...
def show_text(self, string: str, duration: str = '-1', level: int = 0): ...Custom stream protocol registration, Python-based streaming, and generator-based data feeding.
class MPV:
def register_stream_protocol(self, proto: str, open_fn=None): ...
def python_stream(self, name=None, size=None): ... # decorator
def python_stream_catchall(self, cb): ...
def play_bytes(self, data: bytes): ...
class GeneratorStream: ...OpenGL render context management for custom rendering scenarios and integration with graphics frameworks.
class MpvRenderContext:
def __init__(self, mpv: MPV, api_type: str, **kwargs): ...
def render(self, **kwargs): ...
def update(self): ...
def free(self): ...
class MpvOpenGLInitParams: ...
class MpvOpenGLFBO: ...
class MpvRenderParam: ...__version__: str # Library version ('1.0.8')
MPV_VERSION: tuple # MPV API version numbers
fs_enc: str # File system encodingThe library provides structured error handling through custom exception classes:
class ShutdownError(SystemError): ...
class EventOverflowError(SystemError): ...
class PropertyUnavailableError(AttributeError): ...
class ErrorCode:
SUCCESS: int
EVENT_QUEUE_FULL: int
NOMEM: int
INVALID_PARAMETER: int
# ... additional error codesMost operations can raise these exceptions when the underlying mpv operation fails or when the player has been terminated.
class MpvFormat:
NONE: int
STRING: int
INT64: int
DOUBLE: int
FLAG: int
NODE: int
class MpvEventID:
SHUTDOWN: int
START_FILE: int
END_FILE: int
PROPERTY_CHANGE: int
# ... additional event IDs