也许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'看起来像是代表'