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

2020-03-06 03:38发布

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?

1条回答
聊天终结者
2楼-- · 2020-03-06 03:59

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)
查看更多
登录 后发表回答