Skip to content

Instantly share code, notes, and snippets.

@Luciogi
Forked from tiagoengel/noise-cancellation.sh
Created September 14, 2021 11:02
Show Gist options
  • Save Luciogi/517322457aad92af828ee101bd8fb1e4 to your computer and use it in GitHub Desktop.
Save Luciogi/517322457aad92af828ee101bd8fb1e4 to your computer and use it in GitHub Desktop.
Hiss / White / Static noise cancellation on Linux using Pulseaudio and Sox
#!/bin/bash
# You'll need to have sox, pavucontrol and alsa-utils installed, and the snd_aloop kernel module loaded.
# You can configure your system to load it on startup or load it manually with "sudo modprobe snd_aloop"
# Once this is script is running, you need to start recording audio in the application of your
# preference, open pavucontrol, go to the recording tab and change the recording source of that application
# to "Monitor of Loopback ..."
time=5
workDir='/tmp'
sampleRate=44100
# get pulse audio devices
devices=`pactl list | grep -E -A2 '(Source|Sink) #' | grep 'Name: ' | grep -v monitor | cut -d" " -f2`
if [ `echo "$devices" | grep -c aloop` -lt 1 ]; then
echo "No loopback device created. Run 'sudo modprobe snd_aloop' first."
exit
fi
input=`echo "$devices" | grep input.*pci`
output=`echo "$devices" | grep output.*aloop`
record()
{
echo "Recording background noise. Keep quiet for $time seconds."
sleep 3
pacat -r -d $input --latency=1msec | sox -b 16 -c 2 -e signed -t raw -r $sampleRate - -b 16 -c 2 -e signed -r $sampleRate -t wav noise.wav &
PID=$!
sleep $time
kill $PID
aplay noise.wav
}
cd $workDir
if [ ! -f "noise.prof" ] || [ "$1" == "--record" ]; then
# record noise sample and create noise profile
record
sox noise.wav -n noiseprof noise.prof
fi
GREEN='\033[0;32m'
WHITE='\033[1;37m'
NC='\033[0m'
echo -e "
${GREEN}Redirecting the filtered output to $output...${NC}
Start recording in the app of your preference, open pavucontrol, go to the recording tab and change the recoding source to \"Monitor of Loopback ...\".
${WHITE}You'll need to repeat this process for every application (chrome, skype, etc...)${NC}. But this is a persistent configuration, only need to be done once.
"
pacat -r -d $input --latency=1msec | sox -v 0.8 -b 16 -c 2 -e signed -t raw -r $sampleRate - -C 0.5 -b 16 -c 2 -e signed -r $sampleRate -t raw - noisered noise.prof 0.21 | pacat -p -d $output --latency=1msec
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment