#!/usr/bin/env python3 import os import subprocess import random import time import re import sys MUSIC_DIR = os.path.expanduser("~/Music") CARD_NAME_KEYWORD = "Pico Examples Sound Card" def get_music_files(): return [ os.path.join(MUSIC_DIR, f) for f in os.listdir(MUSIC_DIR) if f.lower().endswith(".wav") ] def get_aplay_device_for_card(card_keyword): try: output = subprocess.check_output(["aplay", "-l"], text=True) except subprocess.CalledProcessError as e: print(f"Failed to run 'aplay -l': {e}") sys.exit(1) # Match: card 3: Card [Pico Examples Sound Card], device 0: ... pattern = re.compile(r"card (\d+): .*?\[(.*?)\], device (\d+):") for line in output.splitlines(): match = pattern.search(line) if match: card_num, name, device_num = match.groups() if card_keyword.lower() in name.lower(): return f"plughw:{card_num},{device_num}" print(f"Could not find a matching sound card with keyword '{card_keyword}'") sys.exit(1) def play_track(track, device): print(f"Playing on {device}: {track}") try: subprocess.run(["aplay", "-D", device, track], check=True) except subprocess.CalledProcessError as e: print(f"Failed to play {track} on {device}: {e}") def main(): device = get_aplay_device_for_card(CARD_NAME_KEYWORD) print(f"Using ALSA device: {device}") while True: playlist = get_music_files() if not playlist: print(f"No WAV files found in {MUSIC_DIR}, retrying in 30 seconds...") time.sleep(30) continue random.shuffle(playlist) for track in playlist: play_track(track, device) if __name__ == "__main__": main()