How to convert a wav file -> bytes-like object?
Question: 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: [file.read()](https://docs.python.org/3/library/functions.html#open) 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](https://docs.python.org/3/library/audioop.html), 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](https://docs.python.org/3/library/wave.html) 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)
    

