ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

将字节写入波形文件?

2019-10-27 20:57:47  阅读:284  来源: 互联网

标签:python-3-x byte wav wave python


我在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

您不能混合使用文本和二进制字符串.

标签:python-3-x,byte,wav,wave,python
来源: https://codeday.me/bug/20191027/1947359.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有