0

浪费了很多时间试图在 python 中编写一个波形文件,以发现它在 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 文件。如果我使用 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 中工作,但我不想这样做。

任何打击将不胜感激

4

2 回答 2

2

您将 sample_width 设置为(bit_depth / bits_per_byte)python 2 上的整数和 python 3 上的浮点数。

要在 python 2 和 3 上使用整数除法,请使用(bit_depth // bits_per_byte)

于 2015-12-19T19:09:45.887 回答
2

默认情况下,您需要 floordiv, (bit_depth // bits_per_byte), python2 楼层,python3 默认使用 truediv,因此您float在 python 3中传递 a 而int在 python 2 中传递 an:

wOut.setparams((num_channels, (bit_depth // bits_per_byte), frame_rate, (frame_rate * 12), 'NONE', 'not compressed'))
于 2015-12-19T19:10:11.430 回答