也許wave module可能幫助?
import wave
import struct
import numpy as np
rate = 44100
def sine_samples(freq, dur):
# Get (sample rate * duration) samples on X axis (between freq
# occilations of 2pi)
X = (2*np.pi*freq/rate) * np.arange(rate*dur)
# Get sine values for these X axis samples (as integers)
S = (32767*np.sin(X)).astype(int)
# Pack integers as signed "short" integers (-32767 to 32767)
as_packed_bytes = (map(lambda v:struct.pack('h',v), S))
return as_packed_bytes
def output_wave(path, frames):
# Python 3.X allows the use of the with statement
# with wave.open(path,'w') as output:
# # Set parameters for output WAV file
# output.setparams((2,2,rate,0,'NONE','not compressed'))
# output.writeframes(frames)
output = wave.open(path,'w')
output.setparams((2,2,rate,0,'NONE','not compressed'))
output.writeframes(frames)
output.close()
def output_sound(path, freq, dur):
# join the packed bytes into a single bytes frame
frames = b''.join(sine_samples(freq,dur))
# output frames to file
output_wave(path, frames)
output_sound('sine440.wav', 440, 2)
編輯:
我覺得你的情況,你可能只需要:
packedData = map(lambda v:struct.pack('h',v), fileData)
frames = b''.join(packedData)
output_wave('example.wav', frames)
在這種情況下,你只需要知道的採樣率。檢查波形模塊以獲取有關其他輸出文件參數的信息(即參數爲setparams
方法)。
什麼是'cgi.FieldStorage()'?你也不應該從二進制數據中創建一個字符串。 –
CGI(通用網關接口)是我用來獲取HTTP請求的東西。我的聲音文件二進制數據通過AJAX請求發送,腳本從cgi.FieldStorage中讀取二進制字符串。 – Taztingo
所以你在['cgi'](https://docs.python.org/3/library/cgi.html)模塊中使用Python的構建?在發佈原始聲音數據的情況下,我認爲你根本不應該使用'cgi.FieldStorage'。我忘記了CGI是如何工作的,但我認爲你只是從stdin中讀取數據; 'FieldStorage'看起來像是代表'