Noise Reduction using Spectral Gating

3.0.3 · active · verified Tue Apr 14

NoiseReduce is a Python library for reducing noise in audio signals using a spectral gating algorithm. It offers both a traditional NumPy/SciPy implementation and a more performant PyTorch-based backend for advanced use cases. Currently at version 3.0.3, it is under active development with occasional major updates introducing new features and performance improvements.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to generate a simple noisy audio signal and apply noise reduction using both the default stationary and the more robust non-stationary modes of the `noisereduce.reduce_noise` function. It also includes comments on how to use the optional PyTorch backend for higher performance.

import noisereduce as nr
import numpy as np

# --- 1. Generate dummy noisy audio ---
rate = 44100  # sampling rate
duration = 5  # seconds
t = np.linspace(0, duration, int(rate * duration), endpoint=False)

# Clean signal (e.g., a sine wave)
clean_audio = 0.5 * np.sin(2 * np.pi * 440 * t) # A4 note

# Add some random noise
noise = 0.2 * np.random.randn(len(t))
noisy_audio = clean_audio + noise

# --- 2. Reduce noise ---
# For stationary noise (default and generally faster)
reduced_noise_stationary = nr.reduce_noise(
    y=noisy_audio, 
    sr=rate, 
    stationary=True
)

# For non-stationary noise (e.g., speech with varying background noise)
# This is often more effective but can be slower.
reduced_noise_non_stationary = nr.reduce_noise(
    y=noisy_audio, 
    sr=rate, 
    stationary=False
)

print(f"Original audio shape: {noisy_audio.shape}")
print(f"Reduced audio (stationary) shape: {reduced_noise_stationary.shape}")
print(f"Reduced audio (non-stationary) shape: {reduced_noise_non_stationary.shape}")

# --- Optional: Using the PyTorch backend (requires `pip install noisereduce[torch]`) ---
# try:
#     import torch
#     model = nr.nn.NoiseReduce(sr=rate, nonstationary=False)
#     audio_tensor = torch.from_numpy(noisy_audio).float().unsqueeze(0) # Add batch dim
#     reduced_audio_tensor = model(audio_tensor)
#     reduced_audio_pytorch = reduced_audio_tensor.squeeze(0).numpy()
#     print(f"Reduced audio (PyTorch) shape: {reduced_audio_pytorch.shape}")
# except ImportError:
#     print("PyTorch not installed, skipping PyTorch example.")

view raw JSON →