使用 PyDub 轉換與儲存音訊檔

Python 的口語語言處理

Daniel Bourke

Machine Learning Engineer/YouTube Creator

匯出音訊檔

from pydub import AudioSegment

# 匯入音訊檔
wav_file = AudioSegment.from_file("wav_file.wav")

# 提高 10 分貝 louder_wav_file = wav_file + 10
# 匯出較大聲的音訊檔 louder_wav_file.export(out_f="louder_wav_file.wav", format="wav")
<_io.BufferedRandom name='louder_wav_file.wav'>
Python 的口語語言處理

重設格式並批次匯出音訊檔

def make_wav(wrong_folder_path, right_folder_path):

# 逐一處理格式有誤的檔案 for file in os.scandir(wrong_folder_path):
# 僅處理需要修正的音訊副檔名 if file.path.endswith(".mp3") or file.path.endswith(".flac"):
# 建立新的 .wav 檔名 out_file = right_folder_path + os.path.splitext( os.path.basename(file.path))[0] + ".wav"
# 讀取音訊檔並以 wav 格式匯出 AudioSegment.from_file(file.path).export(out_file, format="wav")
print(f"Creating {out_file}")
Python 的口語語言處理

重設格式並批次匯出音訊檔

# 呼叫新函式
make_wav("data/wrong_formats/", "data/right_format/")
Creating data/right_types/wav_file.wav
Creating data/right_types/flac_file.wav
Creating data/right_types/mp3_file.wav
Python 的口語語言處理

編修與匯出

def make_no_static_louder(static_quiet, louder_no_static):
    # 逐一處理含雜訊且音量偏小的檔案(已為 wav 格式)
    for file in os.scandir(static_quiet_folder_path):

# 建立新檔案路徑 out_file = louder_no_static + os.path.splitext(os.path.basename(file.path))[0] + ".wav"
# 讀取音訊檔 audio_file = AudioSegment.from_file(file.path)
# 去除前 3 秒並提高 10 分貝後匯出 audio_file = (audio_file[3100:] + 10).export(out_file, format="wav") print(f"Creating {out_file}")
Python 的口語語言處理

編修與匯出

# 移除雜訊並提高音量
make_no_static_louder("data/static_quiet/", "data/louder_no_static/")
Creating data/louder_no_static/speech-recognition-services.wav
Creating data/louder_no_static/order-issue.wav
Creating data/louder_no_static/help-with-acount.wav
Python 的口語語言處理

換你了!

Python 的口語語言處理

Preparing Video For Download...