Chuyển đổi và lưu tệp âm thanh với PyDub

Xử lý Ngôn ngữ Nói bằng Python

Daniel Bourke

Machine Learning Engineer/YouTube Creator

Xuất tệp âm thanh

from pydub import AudioSegment

# Nhập tệp âm thanh
wav_file = AudioSegment.from_file("wav_file.wav")

# Tăng thêm 10 decibel louder_wav_file = wav_file + 10
# Xuất tệp âm thanh đã tăng âm lượng louder_wav_file.export(out_f="louder_wav_file.wav", format="wav")
<_io.BufferedRandom name='louder_wav_file.wav'>
Xử lý Ngôn ngữ Nói bằng Python

Đổi định dạng và xuất nhiều tệp âm thanh

def make_wav(wrong_folder_path, right_folder_path):

# Lặp qua các tệp định dạng sai for file in os.scandir(wrong_folder_path):
# Chỉ xử lý các tệp âm thanh cần sửa if file.path.endswith(".mp3") or file.path.endswith(".flac"):
# Tạo tên tệp .wav mới out_file = right_folder_path + os.path.splitext( os.path.basename(file.path))[0] + ".wav"
# Đọc tệp âm thanh và xuất ra định dạng wav AudioSegment.from_file(file.path).export(out_file, format="wav")
print(f"Creating {out_file}")
Xử lý Ngôn ngữ Nói bằng Python

Đổi định dạng và xuất nhiều tệp âm thanh

# Gọi hàm mới của chúng ta
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
Xử lý Ngôn ngữ Nói bằng Python

Xử lý và xuất

def make_no_static_louder(static_quiet, louder_no_static):
    # Lặp qua các tệp có nhiễu nền và nhỏ (đã ở định dạng wav)
    for file in os.scandir(static_quiet_folder_path):

# Tạo đường dẫn tệp mới out_file = louder_no_static + os.path.splitext(os.path.basename(file.path))[0] + ".wav"
# Đọc tệp âm thanh audio_file = AudioSegment.from_file(file.path)
# Cắt 3 giây đầu, tăng 10 decibel và xuất audio_file = (audio_file[3100:] + 10).export(out_file, format="wav") print(f"Creating {out_file}")
Xử lý Ngôn ngữ Nói bằng Python

Xử lý và xuất

# Loại bỏ nhiễu và tăng âm lượng
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
Xử lý Ngôn ngữ Nói bằng Python

Đến lượt bạn!

Xử lý Ngôn ngữ Nói bằng Python

Preparing Video For Download...