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

一个人想着一个人 提交于 2019-12-19 04:33:08

问题


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:


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)


来源:https://stackoverflow.com/questions/35529520/how-to-convert-a-wav-file-bytes-like-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!