The following little script has proven to work well across my devices and regularly does me a good turn, so I thought I'd share it with you, either to use directly or to act as a reference about capturing sound / audio with pulseaudio.
File: pacapture.sh
#!/bin/bash
if ! which sox pacmd parec pactl amixer >/dev/null; then
echo "Need to install some packages"
sudo apt install sox alsa-utils pulseaudio-utils
fi
OUTPUT_FILE="${HOME}/Music/capture/$(date '+%Y-%m-%d-%H-%M-%S').wav"
mkdir -p "${HOME}/Music/capture"
# Get sink monitor:
MONITOR=$(pactl list sinks | grep -o -m 1 'alsa_output\..*\-stereo\.monitor$')
echo "Recording from ${MONITOR} to ${OUTPUT_FILE} ..."
echo "set-source-mute ${MONITOR} false" | pacmd >/dev/null
amixer -q -D pulse sset Master 1%
# Record it raw, and convert to a wav
parec -d "${MONITOR}" | sox -t raw -e signed -r 44100 -L -b 16 -c 2 - "${OUTPUT_FILE}"
Especially notice the line
amixer -q -D pulse sset Master 1%
To actually capture sound, the output to the speaker mustn't be muted. This is important, so while you're capturing sound, never turn the volume to zero. Hence I set the volume to 1%, which is pretty much like muted on my systems (meaning it's so quiet, I don't even hear it). Also note, that I don't have multiple audio devices. If you have multiple devices, you might have to run
pactl list sinks
and adapt the grep pattern to fit your particular environment.