開始使用免費開始

用 PyDub 操作多個音訊檔

你已經看過如何用 PyDub 轉換單一檔案,但如果資料夾裡有多種不同的檔案格式該怎麼辦?

在這個練習中,我們準備了一個 folder,其中包含 good-afternoon 音訊檔的 .mp3.m4a.aac 版本。

我們會用 PyDub 開啟每個檔案,並將它們匯出為 .wav 格式,以便與語音辨識 API 相容。

本練習屬於課程

Python 的口語語言處理

檢視課程

練習說明

  • audio_file 傳入 from_file() 函式。
  • 使用 export() 以格式 ".wav" 匯出 wav_filename

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Loop through the files in the folder
for audio_file in folder:
    
	# Create the new .wav filename
    wav_filename = os.path.splitext(os.path.basename(audio_file))[0] + ".wav"
        
    # Read audio_file and export it in wav format
    AudioSegment.from_file(____).____(out_f=wav_filename, 
                                      format=____)
        
    print(f"Creating {wav_filename}...")
編輯並執行程式碼