Skip to content

Instantly share code, notes, and snippets.

@8lurry
Last active March 21, 2025 16:03
Show Gist options
  • Save 8lurry/a57d61acfd9aa1f120446f8c3d982f97 to your computer and use it in GitHub Desktop.
Save 8lurry/a57d61acfd9aa1f120446f8c3d982f97 to your computer and use it in GitHub Desktop.
Controlling mpv-player/mpv using python scripts..
import os
from mpvclient import mpv
from pathlib import Path
did_pause_at_minimize = False
@mpv.observe_property("window-minimized", mpv.MPV_FORMAT_NODE)
def on_window_minimized(value):
pause = mpv.get_property_bool("pause")
global did_pause_at_minimize
if value:
if not pause:
mpv.set_property_bool("pause", True)
did_pause_at_minimize = True
else:
if did_pause_at_minimize and pause:
mpv.set_property_bool("pause", False)
did_pause_at_minimize = False # Reset to False for probable next cycle
@mpv.add_binding(key="b", name="auto_load_subs")
def auto_load_subs():
path = mpv.get_property_string("path")
srt_path = path.replace(Path(path).suffix , ".srt")
srts = [p for p in os.listdir(str(Path(path).parent)) if p.endswith('.srt')]
if srtsl := len(srts):
if srtsl == 1:
mpv.commandv("sub-add", srts[0])
return
if not os.path.exists(srt_path):
mpv.info(f"Downloading subtitle {srt_path}")
mpv.osd_message("Downloading subtitle ...")
cmd = f"subliminal download -s -f -l en {path}"
resp = os.system(cmd)
if resp < 0:
mpv.warn("Subtitle download failed")
mpv.osd_message("Subtitle download failed")
return
if not os.path.exists(srt_path):
mpv.warn("Subtitle download failed")
mpv.osd_message("Subtitle download failed")
return
mpv.info(f"Subtitle {srt_path} loading ")
mpv.commandv("sub-add", srt_path)
mpv.info(f"Subtitle {srt_path} load succeeded")
mpv.osd_message(f"Subtitle {srt_path} load succeeded")
@mpv.add_binding(key="f", name="set_fscreen")
def fullscreen():
p = mpv.get_property_string("fullscreen")
f = 'yes' if p == 'no' else 'no'
mpv.info(f"fullscreen: '{p}'. Setting to: '{f}'")
mpv.set_property_string("fullscreen", f)
@mpv.add_binding(key="g", name="pause_f")
def pause():
p = mpv.get_property_bool("pause")
mpv.info("unpausing..." if p else "pausing...")
mpv.set_property_bool("pause", not p)
@mpv.add_binding(key="h", name="mpv_utils")
def utils():
mpv.info("fetching mouse pos")
mp = mpv.get_property_node("mouse-pos")
mpv.info(mp)
@mpv.add_binding(key="up")
def volume_up():
v = mpv.get_property_float("volume")
mpv.set_property_float("volume", vn := min(v + 5, 100.0))
mpv.info("volume(was):", v, "new: ", vn)
mpv.osd_message(f"{vn}%")
@mpv.add_binding("down")
def volume_down():
v = mpv.get_property_float("volume")
mpv.set_property_float("volume", vn := max(v - 5, 0.0))
mpv.info("volume(was):", v, "new: ", vn)
mpv.osd_message(f"{vn}%")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment