Introduction
Fieldnote Audio Studio needs short listening previews of its recordings. You will make one three-second WAV, play it, and turn that command into a reusable Bash script. The prepared recordings are original synthetic sounds, not microphone recordings.
You should already know basic Bash arguments, conditions, loops, arrays and functions from Shell for Beginners. This lab explains the media options and quoting you need. FFmpeg is ready to use. The Workspace terminal and Listening Room page share this one container; each lab starts independently.
Make and Play One Preview
In this step, you will hear what a successful preview contains before writing a batch script.
Start in Workspace, which is prepared for UTF-8 filenames. Your working directory is the prepared studio. If a command reports a missing relative path, use pwd to see your current directory and return with this complete cd command. Keep all course work here.
cd /home/labex/project/audio-studio
ls input
You should see Morning bells.wav, 海辺.wav and -closing.wav. Each is an eight-second, mono WAV recording containing 16-bit PCM samples at 22050 samples per second. PCM stores the samples directly. We will preserve that format and keep only the beginning. Only non-hidden, immediate regular files ending in lowercase .wav are inputs; this project does not recursively search subfolders or handle arbitrary codecs.
First create single, a directory for individual experiments. mkdir -p creates it if needed and accepts an existing directory.
mkdir -p single
In the next command, -i identifies the input, -t 3 limits the output to three seconds, and -c:a pcm_s16le selects signed 16-bit PCM audio. Options describe the following input or output, so their positions matter. -v error hides routine progress while keeping errors. -nostdin prevents FFmpeg from reading terminal input for interactive commands, which also makes it safer inside loops. The final path names the output.
Double quotes keep a path containing spaces together as one argument. A leading ./ or an absolute directory prefix also keeps a filename beginning with - from being mistaken for an option. Use a new output file: FFmpeg normally refuses to overwrite an existing file when standard-input interaction is disabled.
ffmpeg -nostdin -v error -i "input/Morning bells.wav" -t 3 -c:a pcm_s16le "single/Morning bells.wav"
A successful conversion prints nothing at this log level. $? is the previous command's native exit status: zero means success, and nonzero means failure. Read it immediately; running another command replaces it.
printf 'Conversion exit: %s\n' "$?"
Expect Conversion exit: 0. This status says the conversion ran successfully; playback will test that the file is usable.
Switch to the Listening Room tab and reload the page. Under First preview, press the play control for Morning bells. Listen to the changing tones, drag the seek control into the clip, and confirm that it ends at three seconds. Select Download WAV to save that same file. The room reads only your actual output files; it cannot fill in missing audio from the library. Return to Workspace to continue.

Look under First preview for the play/seek control and Download WAV link.
If you mistyped the input path, correct the quoted name after checking ls input, then run the command again. If an unwanted experiment already occupies the output name, remove only that exact experiment with rm -- "single/Morning bells.wav" before retrying. -- ends command options; it does not mean “delete everything.” Keep library, archive, notes.txt and scratch-other unchanged throughout this lab.
Give the Conversion a Reusable Function
In this step, you will pass input, output and duration values to the same conversion instead of editing its command for every recording.
Start in Workspace, in /home/labex/project/audio-studio. A function gives a name to a group of commands. Inside make_preview, $1, $2 and $3 are that function's arguments. The script receives its own arguments and forwards them in order. Quoting "$1" preserves each complete path, including spaces and Unicode.
The following here-document writes a small script. cat > preview-one.sh replaces that script file. <<'BASH' takes the following lines as literal text until a line containing only BASH; quoting the delimiter stops your current shell from expanding $1 while saving the script. The first line selects Bash when a script is launched as a program. We will explicitly run it with bash here.
cat > preview-one.sh <<'BASH'
#!/usr/bin/env bash
make_preview() {
ffmpeg -nostdin -v error -i "$1" -t "$3" -c:a pcm_s16le "$2"
}
make_preview "$1" "$2" "$3"
BASH
Use the function to make a different two-second preview. 2 is a duration argument, not part of either filename.
bash preview-one.sh "input/海辺.wav" "single/海辺.wav" 2
printf 'Conversion exit: %s\n' "$?"
Expect zero again. Reload Listening Room, play 海辺 under First preview, and notice that this clip ends at two seconds. Return to Workspace. The same function now works with different paths and durations; the next step adds a collection of inputs.
Process Every Recording
In this step, you will turn the conversion you already tested into a batch by editing the prepared script yourself.
Start in Workspace. The single-file command and preview-one.sh from the preceding steps are your working examples. Our batch accepts exactly three arguments: input directory, new output directory, and an integer duration from one through five seconds. Supply existing, separate input and output-parent directories, keeping output outside input. Do not run concurrent writers against the same output. This first version handles clean inputs; a conversion error must return nonzero but may leave a partial new directory. The next lab adds private publication.
Read the current decisions first
cat -n displays a file with line numbers. It does not change the file:
cat -n batch.sh
Read the existing mkdir -p, the for input and the last exit 0. Before editing, predict two results: would an existing output directory be refused, and would the final status honestly describe a failed conversion? mkdir -p accepts an existing directory, and the unconditional last line reports success. Neither matches the batch you want. Also locate the function definition and its call in your known working example:
cat preview-one.sh
Keep its three-argument conversion; the new decisions belong around it rather than inside FFmpeg. A complete batch should first refuse unsuitable arguments, then collect inputs, then create a new output and convert each member.
Open, locate and edit with nano
Nano is a terminal text editor. Open the actual script, not an output recording:
nano batch.sh
The file contents occupy the main area; the bottom shortcuts use ^ to mean Ctrl. Hold Ctrl while pressing the letter. Use the arrow keys to move. Press Ctrl+W, type exit 0, and press Enter to locate that line. Ctrl+A moves to the start of a line; Ctrl+K cuts that line. Delete the unconditional success line. You can type at the cursor and use Backspace/Delete to correct text. Indentation helps you read nested blocks but does not close them: an if needs fi, and a for needs done.
Work on the following small decisions in this same buffer. Preserve the first #!/usr/bin/env bash line. Do not type shell prompts or Markdown fences into the file.
Refuse bad arguments before creating output
Above the old mkdir, add an argument-count if: when "$#" is not three, use printf 'Usage: batch.sh INPUT OUTPUT SECONDS\n' >&2 and exit 2. You know if, printf and script arguments from the prerequisite; here >&2 directs the explanation to stderr. End each diagnostic with \n so the next prompt starts on a new line.
Next add this small duration decision, still above any directory creation:
case "$3" in
1|2|3|4|5) ;;
*) exit 2 ;;
esac
case "$3" in selects using the third argument. A pattern ends at ): the first pattern accepts one of those five values and needs no action; * matches anything else and exits. ;; ends a branch, and esac closes the complete decision. Predict which branch handles 3, then 0 or three. Keep this guard after the argument-count check so missing arguments are explained first.
Next refuse an existing destination. [ -e path ] tests existence, and [ -L path ] also detects a symbolic link whose target is missing. Between tests, || means OR. This is the condition to put in your if:
[ -e "$2" ] || [ -L "$2" ]
Inside that failure branch, print Output already exists to stderr and exit 2. Close it with fi. Predict why testing only -e would miss one kind of occupied destination. These checks are ordinary error handling, not a concurrency lock.
Collect the real filenames before making a directory
realpath makes the existing input directory absolute, giving each source a safe directory prefix. $(command) captures output; || exit 2 stops if that command fails. Add the input collection after the argument guards and before mkdir:
input=$(realpath -- "$1") || exit 2
shopt -s nullglob
files=("$input"/*.wav)
shopt -s nullglob makes an unmatched *.wav produce no items instead of a literal asterisk path. The quotes protect the directory's spaces; the unquoted glob still matches filenames. The array contains non-hidden immediate lowercase .wav files, as the input contract specifies. ${#files[@]} counts them. Add an if that prints No WAV inputs to stderr and exits 1 when that count equals zero. Place it before directory creation. Predict what an empty directory should leave behind: no published output at all.
Change the old mkdir -p into mkdir -- "$2" || exit 1 after these guards. It now creates a new destination or stops. The caller supplies its existing parent; do not create parent directories or modify unrelated paths.
Apply the known conversion to every array member
Add the same make_preview function definition you read in preview-one.sh; keep its FFmpeg options and quoted function arguments unchanged. Place the definition before the loop. Change the loop's input from the old glob to "${files[@]}", which passes each array member separately. This keeps spaces, Unicode and a leading hyphen in filenames safe.
Inside the loop, compute name=${source##*/}. The ##*/ expansion removes the longest prefix ending in /, leaving the filename. Replace the old direct conversion with a call to make_preview, passing the current source, "$2/$name", and the script's duration "$3", in that order. Put that call in an if ! ...; then branch: ! enters the branch on failure. In the branch, print Could not convert: %s with the filename to stderr, then exit 1. Close the branch and the loop separately.
After done, add a success message using printf 'Published %s previews\n' "${#files[@]}". Only reaching the end of all conversions should report success. Before saving, trace the first iteration for Morning bells.wav: which three arguments reach the function, and which output name is written? Trace -closing.wav too; its absolute source prefix prevents it from being mistaken for an option.
Save, check and recover an editing mistake
Press Ctrl+O to write the file, press Enter to accept the displayed batch.sh filename, then Ctrl+X to exit to Workspace. Saving and leaving are separate actions. If a search or filename prompt is accidental, Ctrl+C cancels that prompt. To abandon unsaved edits, use Ctrl+X and answer N to the save question, then reopen nano batch.sh; this preserves the last saved version. Do not discard wanted changes by answering N accidentally.
bash -n checks syntax without running the conversions:
bash -n batch.sh
printf 'Syntax exit: %s\n' "$?"
Expect no syntax message and Syntax exit: 0. If Bash reports a line error or unexpected end of file, reopen nano batch.sh. Use Ctrl+W to find the nearby if or for, check matching then/fi and do/done, correct just that region, save and exit, then repeat the syntax check. A syntax check does not establish correct behavior; the next runs do that. If nano opened an empty buffer unexpectedly, exit without saving and check pwd and ls before reopening the correct file. Never reset the studio to recover an editing error.
Observe a complete batch and its boundaries
Run your edited script with the clean recordings. Predict the output count before running: one matching WAV per input, with the original filenames and no extra files.
bash batch.sh input previews 3
Expect Published 3 previews. Reload Listening Room. Under Your listening pack, play all three clips, seek within them, and download one. Each lasts three seconds and contains the beginning of its own recording, including -closing. The single-file experiments remain separate.
Back in Workspace, deliberately repeat the command. This is an expected refusal, not a broken environment:
bash batch.sh input previews 3
printf 'Repeat exit: %s\n' "$?"
Expect Output already exists and Repeat exit: 2. Keep that good batch. Check the empty-input decision separately; mkdir -p here creates only this named experiment directory:
mkdir -p empty-input
bash batch.sh empty-input empty-previews 3
printf 'Empty input exit: %s\n' "$?"
Expect No WAV inputs and Empty input exit: 1. List the working directory:
ls
There should be no empty-previews directory. If a decision differs, inspect the relevant region in nano before retrying; leave the successful previews, original library, previous pack and unrelated work intact. You now have a reusable clean-input batch. Next you will improve what happens when a recording is damaged.
Summary
You made playable audio, preserved complete filenames with quotes, and combined a function and array loop into a reusable Bash batch. You read native exit statuses and refused to overwrite an existing listening pack. The next lab adds a staging directory so failed conversions cannot publish a partial new pack.



