Saturday, March 29, 2014

From sound recording to voice/clap activated 9gag scrolling

Record from the microphone in wav format:
arecord out.wav
Or, more conveniently,
rec out.wav

The following commands require the package "sox".

The package sox provides almost everything regarding audio handling. Here is how you can monitor your microphone input without recording it (with a dB monitor, that too, stereo):
rec -n stat

Without the dB monitor:
rec -q -n stat

Show it for 5 seconds then stop:
rec -q -n stat trim 0 5

Repeat after every 5 milliseconds:
while true; do rec -q -n stat trim 0 0.05; done

Repeat after every 5 milliseconds, but only show the Maximum amplitude in that 5ms time interval:
while true; do echo $(rec -q -n stat trim 0 0.05 2>$1 | awk '/^Maximum amplitude/ { print $3}') ; done

Keep recording from standard output and echo 1 if the volume level is above certain threshold   (0.15ms), and return 0 otherwise:
while true; do echo $(rec -n stat trim 0 0.5 2>&1 | awk '/^Maximum amplitude/ { print $3 < .15 ? 0 : 1 }'); done

Following similar command pattern, the following code mutes the master audio level if the input level is more than the threshold, otherwise unmutes:
while true; do amixer set Master $(rec -n stat trim 0 0.5 2>&1 | awk '/^Maximum amplitude/ { print $3 < .15 ? 0 : 1 }'); done

Returns "high" if the amplitude is higher than the threshold, or returns "low":
while true; do ampli=$(rec -q -n stat trim 0 0.25 2>&1 | awk '/^Maximum amplitude/ { print $3 < 0.15 ? 0 : 1 }'); if [ $ampli -eq 1 ]; then echo "high"; else echo "low"; fi; done
(Self-note: Very mysteriously, $3 > 0.15 ? 1 :0 does not work. Why?)

Simulating key stokes:
Package called "xdotool" can send keystroked to X11 like this:
xdotool key k

So, here is the code to simulate a keypress of "j" simulated ny a tap on the mic or a clap:
while true; do ampli=$(rec -q -n stat trim 0 0.25 2>&1 | awk '/^Maximum amplitude/ { print $3 < 0.15 ? 0 : 1 }'); if [ $ampli -eq 1 ]; then xdotool key j; fi; done

This can be used while endlessly scrolling 9gag/facebook page without using hands. Best tool for a forever alone guy.

No comments: