要在Python中使用PyAudio庫進行音頻降噪,您可以使用一些外部庫,如pydub
和noisereduce
。以下是一個簡單的示例,說明如何使用這些庫進行音頻降噪:
首先,確保已安裝所需的庫:
pip install pyaudio
pip install pydub
pip install noisereduce
接下來,創建一個名為audio_noise_reduction.py
的Python文件,并將以下代碼粘貼到其中:
import pyaudio
from pydub import AudioSegment
from noisereduce import reduce_noise
import numpy as np
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
RECORD_SECONDS = 5
def callback(in_data, frame_count, time_info, status):
audio_data = np.frombuffer(in_data, dtype=np.int16)
reduced_noise_data = reduce_noise(audio_data)
return (reduced_noise_data.astype(np.int16).tobytes(), pyaudio.paContinue)
def main():
p = pyaudio.PyAudio()
stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=CHUNK,
stream_callback=callback)
print("開始錄音...")
frames = []
for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
data = stream.read(CHUNK)
frames.append(data)
print("錄音完成。")
stream.stop_stream()
stream.close()
p.terminate()
audio = AudioSegment.from_bytes(b''.join(frames), frame_rate=RATE, sample_width=2, channels=CHANNELS)
noisy_audio = audio.set_frame_rate(RATE)
reduced_noise_audio = reduce_noise(noisy_audio)
reduced_noise_audio.export("reduced_noise_audio.wav", format="wav")
print("降噪完成。音頻已保存為'reduced_noise_audio.wav'")
if __name__ == "__main__":
main()
運行此腳本,它將錄制5秒鐘的音頻,然后使用noisereduce
庫對其進行降噪,并將降噪后的音頻保存到名為reduced_noise_audio.wav
的文件中。
請注意,這個示例僅用于演示目的,實際應用中可能需要對音頻進行更多的預處理和后處理。您可以根據需要調整錄音時間、采樣率和其他參數。