使用Python (wave)讀寫WAV檔案


Python標準庫中的wave模組是一個易於使用的音訊WAV格式介面。該模組中的函式可以將原始格式的音訊資料寫入檔案物件,並讀取WAV檔案的屬性。

檔案以'寫入'或'讀取'模式開啟,就像使用內建的open()函式一樣,但是使用wave模組中的open()函式

wave.open()

此函式開啟一個檔案以讀取/寫入音訊資料。該函式需要兩個引數——第一個是檔名,第二個是模式。模式可以是'wb'(寫入音訊資料)或'rb'(讀取)。

obj = wave.open('sound.wav','wb')

'rb'模式返回一個Wave_read物件,而'wb'模式返回一個Wave_write物件。

Wave_write物件具有以下方法:

close()如果檔案是由wave開啟的,則關閉檔案。
setnchannels()設定聲道數。1表示單聲道,2表示立體聲。
setsampwidth()將樣本寬度設定為n位元組。
setframerate()將幀速率設定為n。
setnframes()將幀數設定為n。
setcomptype()設定壓縮型別和描述。目前,只支援NONE壓縮型別,這意味著不壓縮。
setparams()接受引數元組 (nchannels, sampwidth, framerate, nframes, comptype, compname)
tell()檢索檔案中當前位置。
writeframesraw()寫入音訊幀,不進行校正。
writeframes()寫入音訊幀並確保它們是正確的。

下面的程式碼建立一個持續時間為99999秒的WAV檔案,其中包含隨機的短整型位元組。

import wave, struct, math, random
sampleRate = 44100.0 # hertz
duration = 1.0 # seconds
frequency = 440.0 # hertz
obj = wave.open('sound.wav','w')
obj.setnchannels(1) # mono
obj.setsampwidth(2)
obj.setframerate(sampleRate)
for i in range(99999):
   value = random.randint(-32767, 32767)
   data = struct.pack('<h', value)
   obj.writeframesraw( data )
obj.close()

Wave_read物件方法

close()如果流是由wave模組開啟的,則關閉流。
getnchannels()返回音訊通道數(單聲道為1,立體聲為2)。
getsampwidth()返回樣本寬度(以位元組為單位)。
getframerate()返回取樣頻率。
getnframes()返回音訊幀數。
getcomptype()返回壓縮型別('NONE'是唯一支援的型別)。
getparams()返回一個namedtuple() (nchannels, sampwidth, framerate, nframes, comptype, compname),等效於get*()方法的輸出。
readframes(n)讀取並返回最多n幀音訊,作為位元組物件。
rewind()將檔案指標倒回音訊流的開頭。

下面的程式碼讀取WAV檔案的一些引數。

import wave
obj = wave.open('sound.wav','r')
print( "Number of channels",obj.getnchannels())
print ( "Sample width",obj.getsampwidth())
print ( "Frame rate.",obj.getframerate())
print ("Number of frames",obj.getnframes())
print ( "parameters:",obj.getparams())
obj.close()

輸出

Number of channels 1
Sample width 2
Frame rate. 44100
Number of frames 99999
parameters: _wave_params(nchannels=1, sampwidth=2, framerate=44100, nframes=99999, comptype='NONE', compname='not compressed')

更新於:2020年6月30日

22K+瀏覽量

啟動你的職業生涯

完成課程後獲得認證

開始學習
廣告
© . All rights reserved.