[ prog / sol / mona ]

prog


How do you guys listen to music?

10 2023-10-01 01:34

I just came up wit some scripts to play music :DDD
There are four files, they use mpv internally:

play_song.sh stop_song.sh next_song.sh prev_song.sh

NOTE: These only work properly if there is no instance of mpv running other
than the one they start.

Also, they hold a shared counter variable within /dev/shm

USAGE:

play_song.sh starts a random song from a given directory, when that song ends
it moves to the next song randomly

stop_song.sh stops the current song from playing, if we run play_song.sh after
the same song will start playing

next_song.sh kills the instance of mpv in play_song.sh, this causes the first
script to pick a next script

prev_song.sh kills the instance of mpv in play_song.sh, and it then decrements
a shared counter in /dev/shm, causing the RNG to roll back (thus effectively
playing a previous song)

CODE:

play_song.sh

#!/bin/sh

music_counter="/dev/shm/music_counter"
music_name="/dev/shm/music_name"
music_directory="$HOME/res/snd"
song_count=$(ls $music_directory | wc -l)

while :; do
    # If mpv is already running, ragequit (avoid duplicate instances)
    pgrep mpv > /dev/null && exit 0

    counter=$0
    
    if [ -f $music_counter ]; then
        # If there is a counter, read it
        counter=$(cat $music_counter)
    else 
        # If there is no counter, set it to random number
        counter=$(printf "%d\n" 0x$(xxd -l4 -p /dev/urandom))
        echo $counter > $music_counter
    fi
    
    # Increment the counter
    echo $(expr $counter + 1) > $music_counter
    
    # Generate a random number using the counter as seed
    randno=$(printf "%d\n" 0x$(echo $counter | md5sum | xxd -l4 -p))
    
    # Select a file based on this number
    fileno=$(expr 1 + $(expr $randno % $song_count))
    file=$(ls $music_directory | sed ${fileno}q | tail -n 1)
  
    # Save currently playing song so we can pipe it to script
    echo $file > $music_name

    # Play file, the execution locks here until the song ends
    # or mpv process is killed 
    mpv "$music_directory/$file"
done

stop_song.sh

#!/bin/sh

music_counter="/dev/shm/music_counter"
music_name="/dev/shm/music_name"
music_directory="$HOME/res/snd"

pkill play_song.sh
pkill play_song.sh
pkill mpv

rm -f $music_name

if [ -f $music_counter ]; then
    counter=$(cat $music_counter)

    # We decrement the counter by 1, because play_song.sh
    # will reincrement it
    echo $(expr $counter - 1) > $music_counter
fi

next_song.sh

#!/bin/sh
pkill mpv

prev_song.sh

#!/bin/sh

music_counter="/dev/shm/music_counter"
music_directory="$HOME/res/snd"

if [ -f $music_counter ]; then
    counter=$(cat $music_counter)

    # We decrement the counter by 2 before killing mpv,
    # since the counter will increment by 1 right after
    echo $(expr $counter - 2) > $music_counter

    pkill mpv
fi
40


VIP:

do not edit these