1 year ago

#161348

test-img

Arshaan Khan

High pass and low pass filter using python

I am trying to make a realtime High pass and a low pass filter using Python. What I mean is whenever I play any audio on my computer, I want the low-pass filter to filter the audio in realtime and pass that audio on the left channel (my subwoofer) of my audio amplifier and the High-pass filter to pass audio to my right channel of my audio amplifier (tweeter) and play them simultaneously on left and the right channel.

I was successful in creating a High-pass filter using Python, But it plays it on both channels and it has to be saved to a wav before it is played. I want it to take audio real time from the audio from my computer and then in realtime convert it to go the corresponding right or left audio channels.

Here is the code for the High-pass filter I found on stackoverflow:

import matplotlib.pyplot as plt
import numpy as np
import wave
import sys
import math
import contextlib

fname = 'Lil Nas X  Industry Baby Lyrics ft Jack Harlow.wav'
outname = 'filtered.wav'

cutOffFrequency = 400.0
def running_mean(x, windowSize):
  cumsum = np.cumsum(np.insert(x, 0, 0)) 
  return (cumsum[windowSize:] - cumsum[:-windowSize]) / windowSize

def interpret_wav(raw_bytes, n_frames, n_channels, sample_width, interleaved = True):

    if sample_width == 1:
        dtype = np.uint8 # unsigned char
    elif sample_width == 2:
        dtype = np.int16 # signed 2-byte short
    else:
        raise ValueError("Only supports 8 and 16 bit audio formats.")

    channels = np.fromstring(raw_bytes, dtype=dtype)

    if interleaved:
        # channels are interleaved, i.e. sample N of channel M follows sample N of channel M-1 in raw data
        channels.shape = (n_frames, n_channels)
        channels = channels.T
    else:
        # channels are not interleaved. All samples from channel M occur before all samples from channel M-1
        channels.shape = (n_channels, n_frames)

    return channels

with contextlib.closing(wave.open(fname,'rb')) as spf:
    sampleRate = spf.getframerate()
    ampWidth = spf.getsampwidth()
    nChannels = spf.getnchannels()
    nFrames = spf.getnframes()

    signal = spf.readframes(nFrames*nChannels)
    spf.close()
    channels = interpret_wav(signal, nFrames, nChannels, ampWidth, True)

    freqRatio = (cutOffFrequency/sampleRate)
    N = int(math.sqrt(0.196196 + freqRatio**2)/freqRatio)
    filtered = running_mean(channels[0], N).astype(channels.dtype)

    wav_file = wave.open(outname, "w")
    wav_file.setparams((1, ampWidth, sampleRate, nFrames, spf.getcomptype(), spf.getcompname()))
    wav_file.writeframes(filtered.tobytes('C'))
    wav_file.close()

python

audio

filter

bass

0 Answers

Your Answer

Accepted video resources