我在Python中有一些要输出到WAV文件的数据.现在,我将所有样本生成为短裤,并将它们放入缓冲区.然后,只要缓冲区达到特定长度,我都会打包数据并将其发送到writeframes(在写入每个样本(这很慢)与将整个内容保存在内存中,然后再写入(这很昂贵)之间妥协).
但是它总是抛出TypeError.
output = wave.open(fname, 'wb')
output.setparams((channels, sample_width, sample_rate, 0, 'NONE', 'not compressed'))
# ...generate the data, write to the buffer, then if the buffer is full...
cooked = []
for (ldata, rdata) in rawdata:
cooked.append(struct.pack('<hh',ldata,rdata)) # Pack it as two signed shorts, little endian
output.writeframes(bytes.join(cooked)) # Write to the wave file
我也尝试过”.join(cooked),bytes(cooked),并从一开始就将字节数组煮熟,但是这些似乎都不起作用.
如上
output.writeframes(bytes.join(cooked)) # Write to the wave file
TypeError: descriptor 'join' requires a 'bytes' object but received a 'list'
使用bytes()
output.writeframes(bytes(cooked)) # Write to the wave file
TypeError: 'bytes' object cannot be interpreted as an integer
使煮熟的字节数组
cooked.append(struct.pack('<hh',ldata,rdata)) # Pack it as two signed shorts, little endian
TypeError: an integer is required
直接送入煮熟
TypeError: memoryview: list object does not have the buffer interface
使用”.join()
output.writeframes(''.join(cooked)) # Write to the wave file
TypeError: sequence item 0: expected str instance, bytes found
正确的方法是什么?我无法弄清楚Python到底想要什么.
编辑:使用Python 3.4.1如果会影响任何事情.
解决方法:
您需要这样做:
output.writeframes(b''.join(cooked))
方法的第一个参数是self.如果正常调用该方法,则该参数将自动传递.但是,如果通过Class.method()调用它,则必须手动传递它.由于您传递了一个列表而不是字节对象作为第一个参数,因此您遇到了第一个TypeError.
为了完整起见,以下是其余错误:
output.writeframes(bytes(cooked)) # Write to the wave file
TypeError: 'bytes' object cannot be interpreted as an integer
bytes()接受整数序列;而且,它们一次只有一个字节.对于little-endian,您将需要使用按位运算而不是struct.pack()(例如cook.extend((ldata& 0xFF,ldata>> 8,rdata& 0xFF,rdata>> 8)) 16位整数(假设没有大于0xFFFF且不计负数).
cooked.append(struct.pack('<hh',ldata,rdata)) # Pack it as two signed shorts, little endian
TypeError: an integer is required
同样,bytearray.append()接受一个整数.
output.writeframes(cooked)
TypeError: memoryview: list object does not have the buffer interface
列表不是类似字节的对象,因此writeframes()
不可接受.
output.writeframes(''.join(cooked)) # Write to the wave file
TypeError: sequence item 0: expected str instance, bytes found
您不能混合使用文本和二进制字符串.