Skip to content

Instantly share code, notes, and snippets.

@hedgehog1029
Created November 12, 2019 16:43
Show Gist options
  • Save hedgehog1029/6efa2e943150a88da82b59b6a9f79792 to your computer and use it in GitHub Desktop.
Save hedgehog1029/6efa2e943150a88da82b59b6a9f79792 to your computer and use it in GitHub Desktop.
Play a file and everything after it in the folder via mpv
#!/usr/bin/env python3
from subprocess import Popen, PIPE
import time
import os.path
import socket
import sys
import tempfile
import json
if len(sys.argv) < 2:
print(f"Usage: {sys.argv[0]} <filename>", file=sys.stderr)
sys.exit(2)
filename = sys.argv[1]
filepath = os.path.abspath(filename)
_, ext = os.path.splitext(filename)
tmpdir = tempfile.gettempdir()
ipc_path = os.path.join(tmpdir, "mpv-ipc-0")
movies_dir = os.path.dirname(filepath)
playlist = []
for movfile in os.listdir(movies_dir):
_, cext = os.path.splitext(movfile)
if cext == ext:
playlist.append(os.path.abspath(os.path.join(movies_dir, movfile)))
fmt_playlist = "#EXTM3U\n" + "\n".join(playlist)
print(fmt_playlist)
track_index, _ = next(filter(lambda e: e[1] == filepath, enumerate(playlist)))
mpv_inst = Popen(["mpv", "--idle=yes", f"--input-ipc-server={ipc_path}"], stdin=PIPE, bufsize=0)
time.sleep(1) # yeah so we have to wait for mpv to start the ipc server
sock = socket.socket(family=socket.AF_UNIX)
sock.connect(ipc_path)
def send_command(*args):
payload = json.dumps({ "command": args })
sock.send(payload.encode(encoding="utf-8") + b"\n")
mpv_inst.stdin.write(fmt_playlist.encode("utf-8"))
mpv_inst.stdin.close()
send_command("loadlist", "-")
send_command("set", "playlist-pos", f"{track_index}")
chunk = b""
running = True
while running:
chunk += sock.recv(128)
next_newline = chunk.find(b"\n")
while next_newline > 0:
line = chunk[:next_newline].decode("utf-8")
chunk = chunk[next_newline+1:]
msg = json.loads(line)
# print(msg)
if "event" in msg:
if msg["event"] == "idle":
send_command("quit", "0")
sock.close()
sys.exit(0)
next_newline = chunk.find(b"\n")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment