简体   繁体   English

Python Wave模块仅在v2.7中工作,而在v3.4 Linux中不工作

[英]Python wave module only working in v2.7 not in v3.4 linux

Many hours wasted trying to write a wave file in python to find out that somehow it didn't work on python 3.4.2 but it did work on python 2.7.9 浪费大量时间试图在python中编写wave文件,以发现它在python 3.4.2上不起作用,但在python 2.7.9上却起作用

I'm using Debian jessie and have both versions of python installed. 我正在使用Debian jessie并安装了两个版本的python。 If I just write "python" in my command prompt it launches python 2.7.9 如果我只是在命令提示符下写“ python”,它将启动python 2.7.9

The code I was testing was this: 我正在测试的代码是这样的:

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()

If I run that code with python 2.7.9 I get a healthy wav file with just the wave header. 如果我使用python 2.7.9运行该代码,我将获得仅带有wave标头的健康wav文件。 If I run the same code with python 3.4.2 I get this error: 如果我使用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

And the wave file only contains the first 4 bytes of the header. Wave文件仅包含头的前4个字节。

I haven't found any documentation online stating that this is a problem in python 3.4 so I'm guessing maybe is an issue with my multiversion python installation. 我还没有找到任何在线文档,说明这是python 3.4中的问题,所以我猜测可能是我的multiversion python安装出现问题。

Maybe the wave module I have is only for python 2.7? 也许我拥有的wave模块仅适用于python 2.7? I believe this is not the first time I have this kind of issue, I'm thinking on working only in 2.7 but I would like not to. 我相信这不是我第一次遇到这种问题,我正在考虑仅在2.7中工作,但我不想这样做。

Any hit would be appreciated 任何命中将不胜感激

您需要floordiv (bit_depth // bits_per_byte) ,默认情况下为python2 floor,默认情况下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'))

You set the sample_width to be (bit_depth / bits_per_byte) which is an integer on python 2 and a float on python 3. 您将sample_width设置为(bit_depth / bits_per_byte) ,在python 2上为整数,在python 3上为float。

To use integer division on both python 2 and 3, use (bit_depth // bits_per_byte) 要在python 2和3上都使用整数除法,请使用(bit_depth // bits_per_byte)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM