Pages

星期四, 11月 17, 2011

[python] 讀取訊號

下面範例以聲音訊號為例,示範如何讀取與寫入二元制(binary)檔案。程式碼說明請參考 http://hcliao.twbbs.org/signal-processing-using-python/signal-processing-using-python/read-signal

import scipy.io.wavfile as wav
import numpy as np
import struct
from pylab import *

close('all')
# read .wav file using scipy.io.wavfile module
iWav = wav.read('../voxforgeivr-20070410-062052-1176186024.14/wav/vf3-06.wav')
figure(1)
subplot(2,1,1)
plot(iWav[1])

# write data in binary format to a file
fpBin = open('wav.pcm', 'wb')
for num in iWav[1]:
    data = struct.pack('i', num)
    fpBin.write(data)
fpBin.close()

# read binary data from the file
iResult = array([])
fpBin = open('wav.pcm', 'rb')
iSize = struct.calcsize('i')
while 1:
    data = fpBin.read(iSize)
    if data == '':
        break
    num = struct.unpack('i', data)
    iResult = np.append(iResult, num)
fpBin.close()
subplot(2,1,2)
plot(iResult)
show()

沒有留言:

張貼留言