Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

stopping arecord recording without stopping rest of script

Tags:

bash

I am playing with scripts that use the google speech-to-text api. The api requires flac encoded files so the recording part of the script looks like this:

arecord -q -t wav -d 0 -f S16_LE -r 16000 | flac - -f --best --sample-rate 16000 -s -o "$TEMP_FILE"

This command will record until the user exits with ctrl-c and the wav recorded format should be piped to the flac program for outut in flac format, then the script should continue.

The problem I am having is that pressing ctrl-c ends the script entirely and is cutting off some of the audio (the flac file is still outputted). If I run the script without the pipe:

arecord -q -t wav -d 0 -f S16_LE -r 16000 some.wav

Then pressing ctrl-c will only end the recording and continues on with the script as it should.

How do I fix this so that ctrl-c only stops the arecord command and allows the rest of the script (including the piped flac encoding) to finish?

like image 200
RBI Avatar asked Oct 20 '22 05:10

RBI


1 Answers

Methinks what you're trying to do cannot be done.

Disclaimer: The following is based on my own experiments on Ubuntu 12.04, with just a smattering of research. Do let me know if I'm wrong.

The crux:

  • Pressing Ctrl-C while a pipeline is running sends signal SIGINT to ALL processes in the pipeline.
  • The order in which the processes receive the signal is not guaranteed.
  • Unless ALL processes in the pipeline trap the signal, the script will abort as a whole (though the script itself can trap the signal with a trap command - but such a shell trap won't execute until after the pipeline processes have received the signal and have typically been terminated by it).

In your specific case, arecord is designed to trap SIGINT and exit in an orderly fashion in response.
By contrast, flac appears not to - it is terminated forcefully.
However, even if flac also did trap SIGINT to shut down cleanly, given the nondeterministic order in which the signal is received by the processes involved, you cannot safely use a pipeline with Ctrl-C while expecting overall processing to finish in an orderly fashion.

(As an aside: arecord reports exit code 1 when terminated with Ctrl-C, which makes me wonder how you can distinguish that from true failure, such as running out of disk space.)

Thus:

  • Invoke arecord as a separate command and capture the output in a (temporary) file.
  • Afterward, pass the (temporary) file to flac (and delete the temporary file when done).
like image 124
mklement0 Avatar answered Oct 23 '22 04:10

mklement0