summarylogtreecommitdiffstats
path: root/rolldice.py
blob: 022779ed5afa636978a3299e0bf3c613bd178f16 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#!/usr/bin/env python3
import sys
import os
import random
import termios
import tty
import select
import subprocess
import time
import socket
import json
import tempfile

# ---------- key input ----------
def getch():
    fd = sys.stdin.fileno()
    old = termios.tcgetattr(fd)
    try:
        tty.setcbreak(fd)
        if select.select([sys.stdin], [], [], 0.05)[0]:
            return sys.stdin.read(1)
        return None
    finally:
        termios.tcsetattr(fd, termios.TCSADRAIN, old)

# ---------- music scan ----------
def collect_music(path):
    exts = (".mp3", ".flac", ".wav", ".ogg", ".m4a")
    tracks = []
    for root, _, files in os.walk(path):
        for f in files:
            if f.lower().endswith(exts):
                tracks.append(os.path.join(root, f))
    return tracks

# ---------- mpv ipc ----------
def mpv_cmd(sock, cmd):
    try:
        s = socket.socket(socket.AF_UNIX)
        s.connect(sock)
        s.sendall((json.dumps(cmd) + "\n").encode())
        s.close()
    except:
        pass

# ---------- main ----------
def main():
    if len(sys.argv) < 2:
        print("usage: rolldice <music_dir>")
        sys.exit(1)

    tracks = collect_music(sys.argv[1])
    if not tracks:
        print("no music found")
        sys.exit(1)

    print("🎲 roll the dice")
    print("space: pause | n: next | q: quit")

    try:
        while True:
            track = random.choice(tracks)
            sock = tempfile.mktemp(prefix="rolldice-mpv-")

            print(f"\nâ–¶ {os.path.basename(track)}")

            player = subprocess.Popen([
                "mpv",
                "--no-video",
                "--quiet",
                "--input-terminal=no",
                "--no-input-default-bindings",
                f"--input-ipc-server={sock}",
                track
            ])

            while player.poll() is None:
                key = getch()

                if key == "q":
                    player.terminate()
                    print("\nbye 🎲")
                    return

                if key == "n":
                    player.terminate()
                    break

                if key == " ":
                    mpv_cmd(sock, {"command": ["cycle", "pause"]})

                time.sleep(0.05)

    except KeyboardInterrupt:
        print("\nbye 🎲")

if __name__ == "__main__":
    main()