How to convert a wav file -> bytes-like object?

10,463

file.read() returns a bytes object, so if you're just trying to get the contents of a file as bytes, something like the following would suffice:

with open(filename, 'rb') as fd:
    contents = fd.read()

However, since you're working with audioop, what you need is raw audio data, not raw file contents. Although uncompressed WAVs contain raw audio data, they also contain headers which tell you important parameters about the raw audio. Also, these headers must not be treated as raw audio.

You probably want to use the wave module to parse WAV files and get to their raw audio data. A complete example that reverses the audio in a WAV file looks like this:

import wave
import audioop

with wave.open('intput.wav') as fd:
    params = fd.getparams()
    frames = fd.readframes(1000000) # 1 million frames max

print(params)

frames = audioop.reverse(frames, params.sampwidth)

with wave.open('output.wav', 'wb') as fd:
    fd.setparams(params)
    fd.writeframes(frames)
Share:
10,463
user3535074
Author by

user3535074

Updated on June 04, 2022

Comments

  • user3535074
    user3535074 almost 2 years

    I'm trying to programmatically analyse wav files with the audioop module of Python 3.5.1 to get channel, duration, sample rate, volumes etc. however I can find no documentation to describe how to convert a wav file to the 'fragment' parameter which must be a bytes-like object.

    Can anybody help?

  • user3535074
    user3535074 about 8 years
    Thanks a lot for for help - the question is answered! However I'm getting the expected results on some wav files but not on others. I am receiving the following error: File "C:\Program Files (x86)\Python35-32\lib\wave.py", line 260, in _read_fmt_chunk raise Error('unknown format: %r' % (wFormatTag,)) wave.Error: unknown format: 6 and also: File "C:\Program Files (x86)\Python35-32\lib\chunk.py", line 63, in init raise EOFError EOFError I guess the unknown format error is because of incompatible filetype or compression but the EOF error doesn't make sense to me. Any ideas?
  • marcelm
    marcelm about 8 years
    Python's wave module only supports uncompressed WAVs. The "unknown format" error might be caused by reading compressed WAVs. As for the EOFError, maybe the WAV file is empty or truncated ("cut off")?