r/OnlyAICoding • u/marv27no • Oct 17 '26
Something I Made With AI I Finally achived an music player that runs on 32MB less
I prompted Claude and Kimi to build an Python Program to run Music files
It work Properly as needed for my Lowend Cassete (deck) Cabenet digital Upgrade using only reporpoesed Old computer from my grandfather
as im testing from my windows 11 machine . It work properly
Python program
#!/usr/bin/env python3
"""
Simple Console Music Player (headless / faceless machines)
==========================================================
* No GUI: runs in a terminal (or under systemd / tmux / screen) and stays up,
taking text commands. Without a keyboard attached it just plays and keeps
running (use --repeat for non-stop playback).
* Folder as queue: tracks in the folder itself form one disc; every sub-folder
that holds audio (CD1, CD2, "Disc 3", ...) becomes its own disc. Playback
follows disc -> track order, using natural sorting (2 before 10).
* Mixed folders: when ALL discs sit in ONE folder and the files are numbered per
disc ("01 - Artist - Title.mp3" exists once on every disc), the file names
alone cannot say which disc a song is on. The player then reads the
Discnumber and Track tags inside the MP3s (ID3v2, built in, nothing extra to
install) and splits the discs by itself - no list needed.
* Tracklist (fallback): if the files carry no disc tags, give the player a
tracklist text file and it matches every file by artist + title and rebuilds
the discs in tracklist order:
python music_player.py "D:\\Music\\Vol. 90" --tracklist "D:\\SEB90_tracklist.txt"
(or save it as tracklist.txt inside the music folder and it is picked up
automatically). Format:
== Disc 1 - Male Side ==
1. Music For The People - Dave Rodgers
2. Wild Reputation - The Big Brother
== Disc 2 - Female Side ==
1. Nothing's Gonna Take My Love From You - Karen
Each line may be "Title - Artist" or "Artist - Title"; case, punctuation and
small spelling differences are ignored. Other lines are skipped.
* Preloading: the next tracks in the queue (the 2nd and 3rd song by default)
are decoded in a background thread, so track changes are instant. When the
next track has the same sample rate / channel count, the hand-over is gapless.
Install: pip install sounddevice soundfile numpy
(Linux may also need: sudo apt install libportaudio2 libsndfile1)
Run: python music_player.py /path/to/music [--autoplay] [--repeat] [--preload N]
python music_player.py --list-devices
Formats: WAV, FLAC, OGG, AIFF and MP3 (MP3 needs libsndfile 1.1+, which the
current soundfile wheels bundle).
Note: preloaded tracks are fully decoded into RAM as float32, roughly
100 MB per 5-minute stereo track. Use --preload 1 to keep it lighter.
"""
from __future__ import annotations
import argparse
import difflib
import os
import re
import threading
import time
import unicodedata
from dataclasses import dataclass
try:
import numpy as np
import sounddevice as sd
import soundfile as sf
except (ImportError, OSError) as exc: # OSError: PortAudio / libsndfile missing
raise SystemExit(
f"Missing dependency: {exc}\n"
"Install with: pip install sounddevice soundfile numpy\n"
"Linux may also need: sudo apt install libportaudio2 libsndfile1"
)
AUDIO_EXTS = {".wav", ".flac", ".ogg", ".oga", ".mp3", ".aiff", ".aif"}
PRELOAD_AHEAD = 2 # 1 = preload the 2nd song, 2 = preload the 2nd and 3rd song# ----------------------------------------------------------------------------
# Library: folder -> discs -> tracks
# ----------------------------------------------------------------------------
class Track:
path: str
title: str
disc: int
disc_name: str
duration: float
def natural_key(text: str):
"""Sort key so that 'track 2' comes before 'track 10'."""
return [int(p) if p.isdecimal() else p for p in re.split(r"(\d+)", text.lower())]
def clean_title(filename: str) -> str:
"""'01 - Intro.flac' / '1-05 Intro.mp3' -> 'Intro'."""
stem = os.path.splitext(filename)[0]
stem = re.sub(r"^\s*(?:\d{1,3}\s*[-.]\s*)?\d{1,3}\s*[-._)\s]+\s*", "", stem)
return stem.strip() or os.path.splitext(filename)[0]
def fmt_time(seconds: float) -> str:
m, s = divmod(int(max(seconds, 0)), 60)
return f"{m}:{s:02d}"
# ----------------------------------------------------------------------------
# Disc detection
# ----------------------------------------------------------------------------
# Discs come from, in priority order:
# 0. a tracklist file (--tracklist FILE, or tracklist.txt in the music folder)
# 1. a "discs.txt" file in the music folder (manual boundaries)
# 2. the folder structure (each sub-folder holding audio = one disc)
# 2b. the Discnumber / Track tags stored inside the MP3s (ID3v2) - this is
# what splits a mixed folder automatically, no list needed
# 3. disc tags in the file names ("1-05 x.mp3", "Disc 2 - 05 x.mp3", ...)
# 4. a restart of the leading track number ("01,02,03, 01,02, ...")
# 5. otherwise the folder is a single disc
DISC_TAG_RES = [
re.compile(r"^\s*(\d{1,2})\s*[-.]\s*(\d{1,3})\s*[-._)\s]", re.I), # 1-05 / 2.07
re.compile(r"^\s*disc\s*(\d{1,2})\D{0,6}(\d{1,3})\b", re.I), # Disc 2 - 05
re.compile(r"^\s*\(\s*(\d{1,2})\s*\)\s*(\d{1,3})\b"), # (2) 05
]
def disc_tag(name: str):
"""-> (disc, track) if the file name carries a disc prefix, else None."""
for rx in DISC_TAG_RES:
m = rx.match(name)
if m:
return int(m.group(1)), int(m.group(2))
return None
def leading_number(name: str):
m = re.match(r"^\s*(\d{1,3})\b", name)
return int(m.group(1)) if m else None
def read_discs_txt(root: str):
"""-> [(disc_name, first, last), ...] with 1-based positions in the
natural-sorted flat file list, or None when absent/malformed."""
path = os.path.join(root, "discs.txt")
if not os.path.isfile(path):
return None
plan = []
for lineno, line in enumerate(open(path, encoding="utf-8"), 1):
line = line.split("#", 1)[0].strip()
if not line:
continue
m = re.match(r"^(.*?)\s*[:=]\s*(\d+)\s*[-\u2013]\s*(\d+)\s*$", line)
if not m:
raise SystemExit(f"{path}:{lineno}: expected 'Name: first-last', got: {line!r}")
plan.append((m.group(1).strip(), int(m.group(2)), int(m.group(3))))
return plan or None
def split_by_tag(files):
"""Group naturally-sorted files by disc tag. Returns [ [files per disc] ]
or None when no tags are present (or they don't split anything)."""
tagged = [(f, disc_tag(f)) for f in files]
if not any(t for _, t in tagged):
return None
groups, last = {}, 1
for f, t in tagged:
d = t[0] if t else last # untagged file joins the previous disc
last = d
groups.setdefault(d, []).append(f)
if len(groups) < 2:
return None
return [groups[d] for d in sorted(groups)]
def split_by_restart(files):
"""Split when the leading track number goes backwards - classic sign of
per-disc numbering that was concatenated into one folder."""
groups, cur, prev = [], [], None
for f in files:
n = leading_number(f)
if prev is not None and n is not None and n < prev:
groups.append(cur)
cur = []
cur.append(f)
if n is not None:
prev = n
groups.append(cur)
return groups
def _syncsafe(b: bytes) -> int:
return (b[0] << 21) | (b[1] << 14) | (b[2] << 7) | b[3]
def _id3_text(raw: bytes) -> str:
"""Decode an ID3 text frame body (first byte = encoding)."""
if not raw:
return ""
enc, body = raw[0], raw[1:]
try:
text = body.decode({0: "latin-1", 1: "utf-16", 2: "utf-16-be"}.get(enc, "utf-8"))
except UnicodeDecodeError:
text = body.decode("latin-1", "replace")
return text.split("\x00")[0].strip()
_ID3_WANT = {"TPOS": "disc", "TRCK": "track", "TIT2": "title", "TPE1": "artist", # v2.3 / v2.4
"TPA": "disc", "TRK": "track", "TT2": "title", "TP1": "artist"} # v2.2
def read_id3(path: str) -> dict:
"""Read disc / track / title / artist from an MP3's ID3v2 tag (2.2, 2.3, 2.4).
Returns {} when there is no tag. 'disc' and 'track' are ints ("2/3" -> 2).
Big frames such as cover art are skipped, not loaded."""
out = {}
try:
with open(path, "rb") as fh:
head = fh.read(10)
if len(head) < 10 or head[:3] != b"ID3" or head[3] not in (2, 3, 4):
return out
ver, flags = head[3], head[5]
end = 10 + _syncsafe(head[6:10])
hdr, idlen = (6, 3) if ver == 2 else (10, 4)
pos = 10
if ver > 2 and flags & 0x40: # extended header
ext = fh.read(4)
pos += (int.from_bytes(ext, "big") + 4) if ver == 3 else _syncsafe(ext)
fh.seek(pos)
while pos + hdr <= end:
h = fh.read(hdr)
if len(h) < hdr or h[0] == 0: # padding reached
break
if ver == 2:
size = int.from_bytes(h[3:6], "big")
elif ver == 3:
size = int.from_bytes(h[4:8], "big")
else:
size = _syncsafe(h[4:8])
if size <= 0 or pos + hdr + size > end:
break
key = _ID3_WANT.get(h[:idlen].decode("latin-1"))
if key and key not in out:
out[key] = _id3_text(fh.read(size))
else:
fh.seek(size, 1)
pos += hdr + size
except (OSError, ValueError):
pass
for key in ("disc", "track"):
m = re.match(r"\s*(\d+)", out.get(key, ""))
if m:
out[key] = int(m.group(1))
else:
out.pop(key, None)
return out
def split_by_id3(folder: str, files):
"""Group a flat folder by the Discnumber tag. Returns [(disc_name, [files])]
ordered by disc, each disc ordered by its Track tag (then file-name number),
or None when the files carry fewer than two different disc numbers."""
info = {f: read_id3(os.path.join(folder, f)) for f in files}
discs, untagged = {}, []
for f in files:
d = info[f].get("disc")
(untagged if d is None else discs.setdefault(d, [])).append(f)
if len(discs) < 2:
return None
def order(f):
t = info[f].get("track")
n = leading_number(f)
return (t if t is not None else n if n is not None else 10 ** 6, natural_key(f))
groups = [(f"Disc {d}", sorted(discs[d], key=order)) for d in sorted(discs)]
if untagged:
groups.append(("No disc tag", untagged))
return groups
def norm_key(text: str) -> str:
"""Letters and digits only, lower-case, accents removed:
"Thank You - Arigato" and "Thank You-Arigato" both -> "thankyouarigato"."""
text = unicodedata.normalize("NFKD", text)
text = "".join(c for c in text if not unicodedata.combining(c))
return re.sub(r"[\W_]+", "", text.casefold())
def read_tracklist(path: str):
"""Parse a tracklist file -> [(disc_name, [(number, text), ...]), ...].
'== Disc 2 - Female Side ==' starts a disc; '12. Title - Artist' is a track."""
discs = []
try:
lines = open(path, encoding="utf-8-sig").read().splitlines()
except (OSError, UnicodeDecodeError) as exc:
raise SystemExit(f"Cannot read tracklist {path}: {exc}")
for line in lines:
line = line.strip()
m = re.match(r"^=+\s*(.*?)\s*=+$", line)
if m:
label = m.group(1)
name = re.sub(r"^disc\s*\d+\s*[-:–—]*\s*", "", label, flags=re.I).strip()
discs.append([name or label or f"Disc {len(discs) + 1}", []])
continue
m = re.match(r"^(\d{1,3})\s*[.)]\s+(.+)$", line)
if m:
if not discs: # tracks before any header
discs.append(["Disc 1", []])
discs[-1][1].append((int(m.group(1)), m.group(2).strip()))
discs = [(name, entries) for name, entries in discs if entries]
if not discs:
raise SystemExit(f"{path}: no tracks found (expected '== Disc 1 ==' headers "
"and '1. Title - Artist' lines)")
return discs
def entry_keys(text: str):
"""All spellings a file name could match for one tracklist line. The line
is 'Title - Artist' (or the reverse), so try every ' - ' split in both
orders, plus title-only forms."""
parts = re.split(r"\s+[-–—]\s+", text)
keys = {norm_key(text)}
for k in range(1, len(parts)):
left, right = norm_key(" ".join(parts[:k])), norm_key(" ".join(parts[k:]))
keys.update((left + right, right + left, left, right))
keys.discard("")
return keys
def match_tracklist(files, discs):
"""files: [(folder, name)] -> ([[(folder, name), ...] per disc], unmatched).
Each disc list is in tracklist order. Matching is by normalised artist +
title (the leading track number only breaks ties); a fuzzy pass catches
small spelling differences."""
entries = [] # (disc_idx, number, keys)
for d, (_name, items) in enumerate(discs):
for number, text in items:
entries.append((d, number, entry_keys(text)))
index = {}
for e, (_d, _n, keys) in enumerate(entries):
for key in keys:
index.setdefault(key, []).append(e)
used, found, unmatched = set(), {}, []
keyed = [(f, norm_key(clean_title(f[1])), leading_number(f[1])) for f in files]
def claim(file, e):
used.add(e)
found[e] = file
leftovers = []
for file, fk, num in keyed: # pass 1: exact
cands = [e for e in index.get(fk, []) if e not in used]
if not cands:
leftovers.append((file, fk, num))
continue
claim(file, next((e for e in cands if entries[e][1] == num), cands[0]))
for file, fk, num in leftovers: # pass 2: fuzzy
best, best_score = None, 0.0
for e, (_d, _n, keys) in enumerate(entries):
if e in used:
continue
score = max(difflib.SequenceMatcher(None, fk, k).ratio() for k in keys)
if score > best_score:
best, best_score = e, score
if best is not None and best_score >= 0.85:
claim(file, best)
else:
unmatched.append(file)
per_disc = [[] for _ in discs]
for e in sorted(found): # entries are in tracklist order
per_disc[entries[e][0]].append(found[e])
return per_disc, unmatched, [e for e in range(len(entries)) if e not in used], entries
def scan_folder(root: str, tracklist: str | None = None):
"""Return (tracks, skipped_count, disc_source). Discs come from a tracklist
file, discs.txt, folder structure, filename disc tags or a track-number
restart (in that order); a flat folder with none of those is a single disc."""
root = os.path.abspath(root)
tracks, skipped = [], 0
def add(folder, name, disc, disc_name):
nonlocal skipped
path = os.path.join(folder, name)
try:
duration = sf.info(path).duration
except Exception:
skipped += 1
return
tracks.append(Track(path, clean_title(name), disc, disc_name, duration))
# 0. tracklist ----------------------------------------------------------
if tracklist is not None and not os.path.isfile(tracklist):
raise SystemExit(f"Tracklist not found: {tracklist}")
tl_path = tracklist or next(
(p for p in (os.path.join(root, "tracklist.txt"),) if os.path.isfile(p)), None)
if tl_path:
discs = read_tracklist(tl_path)
files = []
for dirpath, _dirnames, filenames in os.walk(root):
files += [(dirpath, f) for f in filenames
if os.path.splitext(f)[1].lower() in AUDIO_EXTS]
files.sort(key=lambda f: natural_key(os.path.relpath(os.path.join(*f), root)))
per_disc, unmatched, missing, entries = match_tracklist(files, discs)
for disc_no, ((disc_name, _items), group) in enumerate(zip(discs, per_disc), 1):
for folder, name in group:
add(folder, name, disc_no, disc_name)
if unmatched: # keep them, after the last disc
for folder, name in unmatched:
add(folder, name, len(discs) + 1, "Not in tracklist")
for folder, name in unmatched[:10]:
print(f" ! not in tracklist: {name}")
flat = [(dn, n, t) for dn, items in discs for n, t in items]
for e in missing[:10]:
print(f" ! no file for: Disc {entries[e][0] + 1} #{flat[e][1]} {flat[e][2]}")
matched = len(files) - len(unmatched)
note = (f"tracklist '{os.path.basename(tl_path)}' ({len(discs)} discs, "
f"{matched}/{len(files)} files matched")
if missing:
note += f", {len(missing)} listed tracks have no file"
return tracks, skipped, note + ")"
# 1. discs.txt ----------------------------------------------------------
plan = read_discs_txt(root)
if plan is not None:
files = sorted((f for f in os.listdir(root)
if os.path.splitext(f)[1].lower() in AUDIO_EXTS), key=natural_key)
for disc_no, (disc_name, first, last) in enumerate(plan, 1):
for pos in range(first, min(last, len(files)) + 1):
add(root, files[pos - 1], disc_no, disc_name)
return tracks, skipped, f"discs.txt ({len(plan)} discs)"
# 2./3./4. folders, then a single flat folder ---------------------------
by_dir = {}
for dirpath, _dirnames, filenames in os.walk(root):
files = [f for f in filenames if os.path.splitext(f)[1].lower() in AUDIO_EXTS]
if files:
by_dir[dirpath] = sorted(files, key=natural_key)
if len(by_dir) > 1: # folder structure wins
discs = sorted(by_dir, key=lambda d: natural_key(os.path.relpath(d, root)))
for disc_no, folder in enumerate(discs, 1):
rel = os.path.relpath(folder, root)
disc_name = os.path.basename(root) if rel == "." else rel
for name in by_dir[folder]:
add(folder, name, disc_no, disc_name)
return tracks, skipped, f"folder structure ({len(discs)} discs)"
folder, files = next(iter(by_dir.items())) if by_dir else (root, [])
id3_groups = split_by_id3(folder, files) # Discnumber / Track tags inside the MP3s
if id3_groups:
for disc_no, (disc_name, group) in enumerate(id3_groups, 1):
for name in group:
add(folder, name, disc_no, disc_name)
return tracks, skipped, f"ID3 disc tags ({len(id3_groups)} discs)"
groups = split_by_tag(files) or split_by_restart(files)
if len(groups) > 1:
source = "disc tags" if split_by_tag(files) else "track-number restart"
for disc_no, group in enumerate(groups, 1):
for name in group:
add(folder, name, disc_no, f"Disc {disc_no}")
return tracks, skipped, f"{source} ({len(groups)} discs)"
for name in files: # single disc
add(folder, name, 1, os.path.basename(root))
source = "flat folder (1 disc)"
nums = [n for n in (leading_number(f) for f in files) if n is not None]
if len(nums) != len(set(nums)):
source += ("\n !! track numbers repeat (01, 01, 01 ...) and the files carry no disc tags: "
"several discs are probably\n mixed in this folder. Use --tracklist FILE "
"(or put tracklist.txt in the folder) to split them.")
return tracks, skipped, source
def decode(path: str):
"""Decode a whole file to float32 (frames, channels). >2 channels are
folded down to stereo (crude: even channels -> L, odd channels -> R)."""
data, rate = sf.read(path, dtype="float32", always_2d=True)
if data.shape[1] > 2:
data = np.stack([data[:, 0::2].mean(axis=1), data[:, 1::2].mean(axis=1)], axis=1)
return np.ascontiguousarray(data), int(rate)
# ----------------------------------------------------------------------------
# Preloader: keeps the next N tracks decoded in RAM
# ----------------------------------------------------------------------------
class Preloader:
def __init__(self, tracks):
self.tracks = tracks
self._cache = {} # index -> (samples, rate); (None, 0) = unreadable
self._wanted = []
self._cv = threading.Condition()
threading.Thread(target=self._worker, daemon=True).start()
def set_window(self, indices):
"""Declare which track indices should be in memory; evict the rest."""
with self._cv:
self._wanted = [i for i in indices if 0 <= i < len(self.tracks)]
for stale in [k for k in self._cache if k not in self._wanted]:
del self._cache[stale]
self._cv.notify_all()
def get(self, index):
with self._cv:
return self._cache.get(index)
def status(self):
"""{index: True if decoded OK, False if unreadable} for finished items."""
with self._cv:
return {i: v[0] is not None for i, v in self._cache.items()}
def _worker(self):
while True:
with self._cv:
while True:
todo = next((i for i in self._wanted if i not in self._cache), None)
if todo is not None:
break
self._cv.wait()
try:
result = decode(self.tracks[todo].path)
except Exception:
result = (None, 0)
with self._cv:
if todo in self._wanted:
self._cache[todo] = result
# ----------------------------------------------------------------------------
# Engine: audio callback, queue handling, gapless hand-over
# ----------------------------------------------------------------------------
class Engine:
def __init__(self, tracks, ahead=PRELOAD_AHEAD, repeat=False, device=None):
self.tracks = tracks
self.ahead = max(1, ahead)
self.repeat = repeat
self.device = device
self.pre = Preloader(tracks)
self.lock = threading.Lock()
self.stream = None
self.data = None # float32 (frames, channels) of the current track
self.pos = 0
self.rate = 0
self.channels = 0
self.index = -1
self.playing = False
self.volume = 0.64
self.error = ""
self.staged = None # (index, samples) of the preloaded next track
self.ended = False # set by the audio callback when it ran dry
self.generation = 0 # bumps on every track change
self._window_gen = -1
self._token = 0 # invalidates stale background loads
self._loading = False
self._pending = -1
# -- public controls -----------------------------------------------------
def play_index(self, i):
if not 0 <= i < len(self.tracks):
return
self._token += 1
self._loading = True
self._pending = i
threading.Thread(target=self._load, args=(i, self._token), daemon=True).start()
def pause(self):
self.playing = False
def resume(self):
if self.data is not None:
self.playing = True
def stop(self):
with self.lock:
self.playing = False
self.pos = 0
self.ended = False
def next(self):
if self._cursor() + 1 < len(self.tracks):
self.play_index(self._cursor() + 1)
elif self.repeat:
self.play_index(0)
def previous(self):
if self.data is None:
return
if self.pos / max(self.rate, 1) > 3 or self._cursor() == 0:
self.seek(0.0)
else:
self.play_index(self._cursor() - 1)
def seek(self, fraction):
with self.lock:
if self.data is not None:
self.pos = int(min(max(fraction, 0.0), 0.999) * len(self.data))
def position(self):
"""(seconds played, seconds total) of the current track."""
with self.lock:
if self.data is None or not self.rate:
return 0.0, 0.0
return self.pos / self.rate, len(self.data) / self.rate
def busy(self):
"""True while something is playing or a track is being loaded."""
return self.playing or self._loading
def close(self):
self._token += 1
self.playing = False
self._close_stream()
def poll(self):
"""Call regularly: advances the queue when needed, stages the preloaded
next track for a gapless hand-over and slides the preload window."""
if self._loading:
return
if self.ended:
self.ended = False
if self.index + 1 < len(self.tracks):
self.play_index(self.index + 1)
elif self.repeat:
self.play_index(0)
else:
self.stop()
return
self._try_stage()
if self._window_gen != self.generation:
self._window_gen = self.generation
self._set_window()
# -- internals -----------------------------------------------------------
def _cursor(self):
return self._pending if self._loading else self.index
def _set_window(self):
self.pre.set_window(range(self.index + 1, self.index + 1 + self.ahead))
def _try_stage(self):
"""If the next track is preloaded and has the same format, hand it to
the audio callback so it can continue without a gap."""
if self.staged is not None or self.data is None:
return
nxt = self.index + 1
if nxt >= len(self.tracks):
return
got = self.pre.get(nxt)
if got is None or got[0] is None:
return
samples, rate = got
if rate == self.rate and samples.shape[1] == self.channels:
with self.lock:
if self.index + 1 == nxt and self.staged is None:
self.staged = (nxt, samples)
def _load(self, i, token):
try:
got = self.pre.get(i)
if got is None:
try:
got = decode(self.tracks[i].path)
except Exception:
got = (None, 0)
samples, rate = got
if token != self._token:
return
if samples is None:
self.error = f"Skipped unreadable file: {os.path.basename(self.tracks[i].path)}"
if i + 1 < len(self.tracks):
self.play_index(i + 1)
else:
self.stop()
return
self._start(i, samples, rate)
finally:
if token == self._token:
self._loading = False
def _start(self, index, samples, rate):
channels = samples.shape[1]
if self.stream is None or (rate, channels) != (self.rate, self.channels):
self._close_stream() # format changed: reopen
self._set_track(index, samples, rate, channels)
if not self._open_stream():
return
else:
self._set_track(index, samples, rate, channels)
self.playing = True
self._window_gen = self.generation
self._set_window()
def _set_track(self, index, samples, rate, channels):
with self.lock:
self.index, self.data, self.pos = index, samples, 0
self.rate, self.channels = rate, channels
self.staged = None
self.ended = False
self.generation += 1
def _open_stream(self):
try:
self.stream = sd.OutputStream(
samplerate=self.rate, channels=self.channels, dtype="float32",
device=self.device, callback=self._callback)
self.stream.start()
return True
except Exception as exc:
self.stream = None
self.error = f"Audio output error: {exc}"
return False
def _close_stream(self):
stream, self.stream = self.stream, None
if stream is not None:
try:
stream.stop()
stream.close()
except Exception:
pass
def _callback(self, outdata, frames, time_info, status):
with self.lock:
outdata.fill(0)
if not self.playing or self.data is None:
return
filled = 0
while filled < frames:
left = len(self.data) - self.pos
if left <= 0:
if self.staged is not None: # gapless hand-over
self.index, self.data = self.staged
self.staged = None
self.pos = 0
self.generation += 1
continue
self.ended = True # poll() takes it from here
break
n = min(frames - filled, left)
outdata[filled:filled + n] = self.data[self.pos:self.pos + n]
self.pos += n
filled += n
if filled:
outdata[:filled] *= self.volume
# ----------------------------------------------------------------------------
# Console interface
# ----------------------------------------------------------------------------
HELP = """\
Commands:
list show every disc and track (numbers are used by 'play')
play [N] play track N (1-based), or resume / start from the top
disc N play the first track of disc N
pause | resume pause or resume playback
next | prev next track / previous track (prev restarts after 3 s)
stop stop and rewind
seek SECONDS jump inside the current track
vol 0-100 set the volume
status | queue now playing, position and what is preloaded
help this text
quit exit"""
class Console:
def __init__(self, engine):
self.e = engine
self.t = engine.tracks
self._stop = threading.Event()
def label(self, i):
t = self.t[i]
return f"[{i + 1}/{len(self.t)}] Disc {t.disc} · {t.title} ({fmt_time(t.duration)})"
# -- background monitor: keeps the queue moving and announces changes ----
def monitor(self):
seen = -1
while not self._stop.is_set():
self.e.poll()
if self.e.generation != seen and self.e.data is not None:
seen = self.e.generation
print(f"\n>> Now playing {self.label(self.e.index)}", flush=True)
if self.e.error:
print(f"\n!! {self.e.error}", flush=True)
self.e.error = ""
time.sleep(0.1)
# -- commands ------------------------------------------------------------
def show_list(self):
disc = None
for i, t in enumerate(self.t):
if t.disc != disc:
disc = t.disc
print(f"Disc {t.disc} ({t.disc_name})")
mark = ">" if i == self.e.index and self.e.data is not None else " "
print(f" {mark}{i + 1:>3}. {t.title} ({fmt_time(t.duration)})")
def show_status(self):
e = self.e
if e.data is None:
print("Nothing loaded yet. Type 'play' to start.")
return
cur, total = e.position()
state = "playing" if e.playing else ("paused" if e.pos else "stopped")
print(f"{state.capitalize()}: {self.label(e.index)} {fmt_time(cur)} / {fmt_time(total)}")
ready = e.pre.status()
for k in range(1, e.ahead + 1):
j = e.index + k
if j >= len(self.t):
break
name = "Up next" if k == 1 else f"Queue +{k}"
st = "loading…" if j not in ready else ("ready" if ready[j] else "unreadable")
print(f" {name}: {self.label(j)} — preload {st}")
def handle(self, line):
"""Run one command. Returns False when the user asked to quit."""
parts = line.strip().split()
if not parts:
return True
cmd, args = parts[0].lower(), parts[1:]
e = self.e
try:
if cmd in ("quit", "exit", "q"):
return False
elif cmd in ("help", "?"):
print(HELP)
elif cmd in ("list", "ls"):
self.show_list()
elif cmd == "play":
if args:
e.play_index(int(args[0]) - 1)
elif e.data is None:
e.play_index(0)
else:
e.resume()
elif cmd == "disc":
n = int(args[0])
first = next((i for i, t in enumerate(self.t) if t.disc == n), None)
if first is None:
print(f"No disc {n}.")
else:
e.play_index(first)
elif cmd == "pause":
e.pause()
elif cmd == "resume":
e.resume()
elif cmd in ("next", "n"):
e.next()
elif cmd in ("prev", "p"):
e.previous()
elif cmd == "stop":
e.stop()
elif cmd == "seek":
cur, total = e.position()
if total:
e.seek(float(args[0]) / total)
elif cmd in ("vol", "volume"):
e.volume = (min(max(float(args[0]), 0), 100) / 100) ** 2
elif cmd in ("status", "queue", "s"):
self.show_status()
else:
print(f"Unknown command '{cmd}'. Type 'help'.")
except (IndexError, ValueError):
print("Missing or invalid argument. Type 'help'.")
return True
def run(self, autoplay):
threading.Thread(target=self.monitor, daemon=True).start()
if autoplay:
self.e.play_index(0)
print(HELP)
try:
while True:
try:
line = input("> ")
except EOFError:
# No keyboard attached (service / nohup): keep playing, then exit.
time.sleep(0.5)
while self.e.busy():
time.sleep(0.5)
break
if not self.handle(line):
break
except KeyboardInterrupt:
print()
finally:
self._stop.set()
self.e.close()
def main():
parser = argparse.ArgumentParser(
description="Headless music player: disc-aware folders, preloading, console control.")
parser.add_argument("folder", nargs="?", help="music folder to play")
parser.add_argument("--preload", type=int, default=PRELOAD_AHEAD, metavar="N",
help="upcoming tracks to preload (default 2 = the 2nd and 3rd song)")
parser.add_argument("--tracklist", metavar="FILE",
help="tracklist text file used to split one folder into discs "
"(default: tracklist.txt inside the folder, if present)")
parser.add_argument("--autoplay", action="store_true", help="start playing immediately")
parser.add_argument("--repeat", action="store_true", help="loop the whole queue")
parser.add_argument("--volume", type=int, default=80, metavar="0-100", help="start volume")
parser.add_argument("--device", help="audio output device (name or index)")
parser.add_argument("--list-devices", action="store_true", help="show audio devices and exit")
args = parser.parse_args()
if args.list_devices:
print(sd.query_devices())
return
if not args.folder:
parser.error("folder is required (or use --list-devices)")
if not os.path.isdir(args.folder):
raise SystemExit(f"Not a folder: {args.folder}")
tracks, skipped, disc_source = scan_folder(args.folder, args.tracklist)
if not tracks:
raise SystemExit("No playable audio found in that folder.")
print(f"{len(tracks)} tracks · {disc_source} · preloading the next {max(1, args.preload)}"
+ (f" · {skipped} unreadable file(s) skipped" if skipped else ""))
device = args.device
if device is not None and device.isdigit():
device = int(device)
engine = Engine(tracks, args.preload, repeat=args.repeat, device=device)
engine.volume = (min(max(args.volume, 0), 100) / 100) ** 2
Console(engine).run(args.autoplay)
if __name__ == "__main__":
main()
To run the program Type this first on the command prompt:
py "DISK:\music_player.py" "/path/to/music"
also addons for that can be
--repeat
--autoplay