I found a kind of shaky way that sort of solves this problem.
I noticed that when silence is detected, sox naturally won't append anything more to the file until it hears more sound. So I decided I could try and take advantage of this fact.
First of all, I start up sox's sound recorder in the background:
rec /tmp/recording.flac rate 32k silence 1 0.1 3% -1 3.0 3% &
Next I get the PID of the recording process with: p=$!
Then I give the recording process a second to finish starting up, and then wait until the file starts to grow.
sleep 1
until [ "$var1" != "$var2" ]; do
var1=`du "/tmp/recording.flac"`
sleep 1
var2=`du "/tmp/recording.flac"`
done
After this loop breaks, that means that sound has been detected. So now I create another loop to wait until data stops being appended to the file (This will happen once sox detects silence again).
echo "Sound Detected"
until [ "$var1" == "$var2" ]; do
var1=`du "/tmp/recording.flac"`
sleep 0.5
var2=`du "/tmp/recording.flac"`
done
Now I just need to quit rec
:
echo "Silence Detected"
kill $p
And that's it.
Here is the completed script:
rec /tmp/recording.flac rate 32k silence 1 0.1 3% -1 3.0 3% &
p=$!
sleep 1
until [ "$var1" != "$var2" ]; do
var1=`du "/tmp/recording.flac"`
sleep 1
var2=`du "/tmp/recording.flac"`
done
echo "Sound Detected"
until [ "$var1" == "$var2" ]; do
var1=`du "/tmp/recording.flac"`
sleep 0.5
var2=`du "/tmp/recording.flac"`
done
echo "Silence Detected"
kill $p
Now I would prefer a better, more stable way to do this, but this will have to work for now.