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

user3535074 picture user3535074 · Feb 20, 2016 · Viewed 8.4k times · Source

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?

Answer

marcelm picture marcelm · Feb 21, 2016

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)