Получение ошибки при выполнении дискретизации обработки аудиосигнала с использованием фильтра нижних частот в python

#python #numpy #scipy #signal-processing #lowpass-filter

Вопрос:

Я хочу выполнить дискретизацию аудиосигнала, вводя нули между образцами, чтобы создать более длинный сигнал с коэффициентом N=2 . частота дискретизации составляет 44100 Гц, время = 5 сек

 fs = 44100

def butter_lowpass(cutoff, fs, order=5):
    nyq = 2 * fs
    normal_cutoff = cuto[enter image description here][1]ff / nyq
    b, a = butter(order, normal_cutoff, btype='low', analog=False)
    return b, a


def butter_lowpass_filter(data, cutoff, fs, order=5):
    b, a = butter_lowpass(cutoff, fs, order=order)
    y = lfilter(b, a, data)
    return y


# Filter requirements.
order = 6
fs = 44100  # sample rate, Hz
cutoff = 8000  # desired cutoff frequency of the filter, Hz

y = butter_lowpass_filter(data, cutoff, fs, order)
# Get the filter coefficients so we can check its frequency response.
b, a = butter_lowpass(cutoff, fs, order)

plt.figure()
plt.subplot(211)
plt.plot(signal, color='green')
plt.grid(color='green', linestyle='--', linewidth=0.5)
plt.title('original signal')

plt.subplot(212)
plt.plot(y, color='red')
plt.title('Filtered')
plt.grid(color='green', linestyle='--', linewidth=0.5)
plt.show(block=True)
 

Я использую следующие модули от начала записи до остановки записи и открытия записи файла .wav.

 import numpy as np
import matplotlib.pyplot as plt
import pyaudio  # Soundcard audio I/O access library
import wave  # Python 3 module for reading / writing simple .wav files
from scipy.signal import butter, lfilter
from scipy.io import wavfile

FORMAT = pyaudio.paInt16  # data type formate
CHANNELS = 2  # Adjust to your number of channels
RATE = 44100  # Sample Rate

CHUNK = 512  # Block Size
RECORD_SECONDS = 5  # Record time
WAVE_OUTPUT_FILENAME = "file3.wav"

# Startup pyaudio instance
audio = pyaudio.PyAudio()

# start Recording
stream = audio.open(format=FORMAT, channels=CHANNELS,
                    rate=RATE, input=True,
                    frames_per_buffer=CHUNK)
print("recording...")
frames = []

# print(int(RATE / CHUNK * RECORD_SECONDS))
print()
# Record for RECORD_SECONDS
for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
    data = stream.read(CHUNK)
    frames.append(data)
print("finished recording")

# Stop Recording
stream.stop_stream()
stream.close()
audio.terminate()

waveFile = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
waveFile.setnchannels(CHANNELS)
waveFile.setsampwidth(audio.get_sample_size(FORMAT))
waveFile.setframerate(RATE)
waveFile.writeframes(b''.join(frames))
waveFile.close()
# Finished Recording Procedure


#    Opening Wav file for Plotting 

spf = wave.open("file3.wav", "r")

# Extract Raw Audio from Wav File
signal = spf.readframes(-1)
signal = np.frombuffer(signal, dtype=np.int16)
 

I know that for Upsampling, I need Nyquist = 2Fs after passing it to the Low pass signal. While designing low pass filter and updating sampling rate my resulting rate still dropping to 22100Hz. Morover I am unable to figure out cutoff freq But in this example I have mentioned as 8000Hz.