浪费了很多时间试图在python中编写一个wave文件,以发现它不能在python 3.4.2上运行但是它确实可以在python 2.7.9上运行
我正在使用Debian jessie并安装了两个版本的python。如果我只是写" python"在我的命令提示符下,它启动python 2.7.9
我正在测试的代码是:
import wave
frame_rate = 44100
bit_depth = 16
bits_per_byte = 8
num_channels = 2
wOut = wave.open("out.wav","w")
wOut.setparams((num_channels, (bit_depth / bits_per_byte), frame_rate, (frame_rate * duration), 'NONE', 'not compressed'))
wOut.close()
如果我用python 2.7.9运行该代码,我会得到一个健康的wav文件,只有wave头。 如果我使用python 3.4.2运行相同的代码,我会收到此错误:
File "/usr/lib/python3.4/wave.py", line 433, in close
self._ensure_header_written(0)
File "/usr/lib/python3.4/wave.py", line 455, in _ensure_header_written
self._write_header(datasize)
File "/usr/lib/python3.4/wave.py", line 472, in _write_header
self._sampwidth * 8, b'data'))
struct.error: required argument is not an integer
波形文件只包含标题的前4个字节。
我还没有在网上找到任何文档说明这是python 3.4中的问题所以我猜测可能是我的多版本python安装的问题。
也许我拥有的wave模块仅适用于python 2.7? 我相信这不是我第一次遇到这样的问题,我只考虑在2.7工作,但我不愿意。
任何打击都会受到赞赏
答案 0 :(得分:2)
默认情况下你需要floordiv,(bit_depth // bits_per_byte)
,python2楼层,python3默认使用truediv,所以你在python 3中传递float
而在python 2中传递int
:
wOut.setparams((num_channels, (bit_depth // bits_per_byte), frame_rate, (frame_rate * 12), 'NONE', 'not compressed'))
答案 1 :(得分:1)
您将sample_width设置为(bit_depth / bits_per_byte)
,这是python 2上的整数和python 3上的浮点数。
要在python 2和3上使用整数除法,请使用(bit_depth // bits_per_byte)