简体   繁体   中英

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

I'm using Debian jessie and have both versions of python installed. If I just write "python" in my command prompt it launches 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. If I run the same code with python 3.4.2 I get this error:

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.

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.

Maybe the wave module I have is only for 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.

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.

To use integer division on both python 2 and 3, use (bit_depth // bits_per_byte)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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