位元組轉整數
你已經看過如何用 Python 的 wave 模組和 readframes() 方法匯入並讀取音訊檔。不過這樣做會得到一個位元組(bytes)陣列。
為了把位元組轉成更好用的型別,我們會使用 NumPy 的 frombuffer() 方法。
把聲波的位元組傳給 frombuffer(),並將 dtype 指定為 'int16',就能把位元組轉成整數。整數比位元組更容易處理。
Python 的 wave 函式庫和 good_morning.wav(音訊檔)都已經匯入。
本練習屬於課程
Python 的口語語言處理
練習說明
- 以常見別名
np匯入numpy套件。 - 開啟並讀取「good morning」音訊檔。
- 將
signal_gm的位元組轉為int16整數。 - 檢視前 10 個聲波數值。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
import ____ as ____
# Open good morning sound wave and read frames as bytes
good_morning = wave.open(____, 'r')
signal_gm = good_morning.readframes(-1)
# Convert good morning audio bytes to integers
soundwave_gm = np.frombuffer(____, dtype=_____)
# View the first 10 sound wave values
print(soundwave_gm[:____])