首頁 > 易卦

使用python讀寫聲音檔案wav

作者:由 whoispo 發表于 易卦日期:2021-12-04

怎樣建立wav的聲音檔案

wav檔案是一種無損的音訊檔案。python讀寫這種這種檔案比較方便,因為python自帶有標準庫

“wave”

,可以用來讀寫這種檔案。

import waveimport numpy as npdef my_read_wave(filename: str): ifile = wave。open(filename) channels = ifile。getnchannels() fs = ifile。getframerate() frames_n = ifile。getnframes() sample_width = ifile。getsampwidth() # 獲取frames_n幀資料(每幀位元組數: sample_width * channels) # x為位元組陣列 x = ifile。readframes(frames_n) ifile。close() if sample_width == 2: x = np。frombuffer(x, dtype=np。uint16) # 位元組陣列轉換成uint16的陣列 x = x。astype(np。int16) # 將uint16陣列轉換成 x = x。astype(np。float) / (2**15-1) x = x。reshape((-1, channels)) return x, fsdef my_write_wave(filename:str, x: np。ndarray, fs: int): ofile = wave。open(filename, “w”) ofile。setsampwidth(2) ofile。setframerate(fs) if x。ndim == 1: ofile。setnchannels(1) else: m, n = np。shape(x) ofile。setnchannels(n) x = x。flatten() x = x * (2**15-1) x = x。astype(np。int16) x = x。astype(np。uint16) ofile。writeframesraw(x。tobytes()) ofile。close()

測試一下,讀寫檔案

x, fs = my_read_wave(“sounds/castanets。wav”)plt。figure()plt。plot(x[:, 0])plt。figure()plt。plot(x[:, 1])my_write_wave(“s。wav”, x, fs)

使用python讀寫聲音檔案wav