如何转换WAV文件->像字节的对象? [英] How to convert a wav file -> bytes-like object?

查看:133
本文介绍了如何转换WAV文件->像字节的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Python 3.5.1的audioop模块以编程方式分析wav文件,以获取频道,持续时间,采样率,音量等.但是我找不到任何文档来描述如何将wav文件转换为片段"参数,该参数必须是类似字节的对象.

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.

有人可以帮忙吗?

推荐答案

文件. read()返回一个bytes对象,因此,如果您只是尝试以bytes的形式获取文件的内容,则满足以下条件:

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()

但是,由于您正在使用 audioop ,因此您需要的是原始的音频数据,而不是原始的文件内容.尽管未压缩的WAV包含原始音频数据,但它们还包含标头,这些标头告诉您有关原始音频的重要参数.另外,这些标头不得视为原始音频.

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.

您可能想使用 wave 模块来解析WAV文件并获取原始音频数据.反转WAV文件中音频的完整示例如下:

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)

这篇关于如何转换WAV文件->像字节的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆