This script removes background noise and enhances the quality of a .wav audio file using spectral gating in PyTorch and Torchaudio.
- 📥 Takes a noisy
.wavfile as input - 🧠 Applies spectral gating to suppress background noise
- 🎧 Outputs a cleaned and enhanced
.wavfile - ⚡ Runs on GPU (CUDA) if available
-
Load Audio: Uses
torchaudio.load()and resamples to 16kHz (default for models like Whisper). -
Spectral Gating: Converts waveform to spectrogram → estimates background noise → subtracts it → reconstructs waveform.
-
Save Clean Audio: Stores the denoised waveform as a
.wavfile.
audio_denoise_enhance.py # Main script
input.wav # Example input (your noisy audio)
output.wav # Output (cleaned audio)
pip install torch torchaudioMake sure your system has a GPU with CUDA if you want GPU acceleration.
python denoise.py input.wav output.wavinput.wav: Path to your noisy audio fileoutput.wav: Path where cleaned audio will be saved
- The first 0.5 seconds of the input audio are assumed to contain background noise only (used for noise estimation).
- Spectral gating helps suppress constant low-level noise like fan hum, air conditioning, etc.
- You can modify
n_fftorhop_lengthin thespectral_gate_denoise()function for finer control.
python denoise.py noisy_speech.wav cleaned_speech.wavSpectral gating is a noise reduction technique that suppresses low-energy (noisy) frequencies in a spectrogram while preserving high-energy components (speech/music).