Python Audio Noise Cleaner

import librosa

import numpy as np

import noisereduce as nr

import soundfile as sf

import os


# --------------------------------------------------

# CONFIG

# --------------------------------------------------

NOISE_DURATION = 1.0   # seconds used to estimate noise

OUTPUT_SUFFIX = "_cleaned"


# --------------------------------------------------

# Load audio

# --------------------------------------------------

def load_audio(path):

    audio, sr = librosa.load(path, sr=None, mono=True)

    return audio, sr


# --------------------------------------------------

# Noise reduction

# --------------------------------------------------

def reduce_noise(audio, sr, noise_duration=NOISE_DURATION):

    noise_samples = int(noise_duration * sr)

    noise_clip = audio[:noise_samples]


    reduced = nr.reduce_noise(

        y=audio,

        sr=sr,

        y_noise=noise_clip,

        prop_decrease=1.0

    )

    return reduced


# --------------------------------------------------

# Save cleaned audio

# --------------------------------------------------

def save_audio(original_path, audio, sr):

    base, ext = os.path.splitext(original_path)

    output_path = f"{base}{OUTPUT_SUFFIX}.wav"

    sf.write(output_path, audio, sr)

    return output_path


# --------------------------------------------------

# MAIN

# --------------------------------------------------

if __name__ == "__main__":

    input_path = input("Enter audio file path (.wav/.mp3): ").strip()


    if not os.path.exists(input_path):

        print(" File not found.")

        exit()


    print(" Loading audio...")

    audio, sr = load_audio(input_path)


    print(" Reducing background noise...")

    cleaned_audio = reduce_noise(audio, sr)


    output = save_audio(input_path, cleaned_audio, sr)


    print("\n Noise reduction complete!")

    print(f" Cleaned file saved as: {output}")


No comments: