Search code examples
linuxbashmpv

How to play a sound file while running a program in Bash


I'm creating an alarm clock script as I haven't found a good Linux alarm yet and I decided it would be a good idea to learn Bash scripting(again). I'm looking into making a program that plays an alarm sound(beep beep full volume) and I want the program to make me solve some basic algebra before it turns off the sound. However I can't figure out how to play the sound at the same time it's asking for solutions and waiting for my input so it could turn the noise off. I really don't even know what expression I would use to force mpv to act strictly in the background. & and ; wait for the line to terminate and I wasn't able to solve it by using parallel. I also tried to direct output to /dev/null because that seemed to be the answer for other people but it doesn't work for my problem(nothing happens until mpv terminates, which only seems obvious because it only ignores output right?).

Here's what I've done so far(extremely basic and only has the structure so I can program with it):

 # !/bin/zsh

 function math (){ 
     echo MATH
     read answer
     if (( ("$answer") == $1 )); then
         echo PASS    
     else
         echo FAIL
     fi  
 }

 echo 'Alarm'

 let "NUM1=(($RANDOM % 10) * 3)";
 let "NUM2=(($RANDOM % 10) * 3)";

 let "m = $NUM1 * $NUM2"

 printf "%d * %d = %d" "$NUM1" "$NUM2" "$m"

 mpv alarm_sound.wav ; #>/dev/null 2>&1
 math m

echo MATH comes after mpv has finished playing the sound.

My dream would be to have mpv to act as a completely independent process so that it affects alarm.sh in no way and then kill -9 mpv once the if condition "passes".

I'm completely lost - thanks in advance!


Solution

  • As usual with Linux, there are many viable solutions to your dilemma.

    The most simple that comes to mind is to enter the & sign at the end of your command:

    mpv audio_file.wav &
    

    This should spawn a new process for the audio file.