Advertisement
BaSs_HaXoR

Noise Filter for wave files via Python

Oct 15th, 2024
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.17 KB | None | 0 0
  1. import numpy as np
  2. import scipy.io.wavfile as wav
  3. from scipy.signal import butter, sosfilt
  4.  
  5. def filter_frequency(input_file, output_file, freq_to_remove, order=5):
  6.     """
  7.    Filters a specific frequency from a WAV file.
  8.  
  9.    Args:
  10.        input_file (str): Path to the input WAV file.
  11.        output_file (str): Path to save the filtered WAV file.
  12.        freq_to_remove (float): Frequency to remove in Hz.
  13.        order (int): Order of the Butterworth filter (default: 5).
  14.    """
  15.  
  16.     # Read the WAV file
  17.     fs, data = wav.read(input_file)
  18.  
  19.     # Design a bandstop filter
  20.     nyquist = 0.5 * fs
  21.     low = (freq_to_remove - 5) / nyquist
  22.     high = (freq_to_remove + 5) / nyquist
  23.     sos = butter(order, [low, high], btype='bandstop', analog=False, output='sos')
  24.  
  25.     # Apply the filter
  26.     filtered_data = sosfilt(sos, data)
  27.  
  28.     # Write the filtered data to a new WAV file
  29.     wav.write(output_file, fs, filtered_data.astype(np.int16))
  30.  
  31. if __name__ == "__main__":
  32.     input_file = "your_audio_file.wav"
  33.     output_file = "filtered_audio.wav"
  34.     freq_to_remove = 60  # Example: remove 60 Hz hum
  35.     filter_frequency(input_file, output_file, freq_to_remove)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement