Python Wave 库字符串到字节

标签 python python-2.7 wav

所以基本上我试图读取波形文件的信息,以便我可以获取字节信息并创建时间->幅度点的数组。

import wave

class WaveFile:

    # `filename` is the name of the wav file to open
    def __init__(self, fileName):
        self.wf = wave.open(fileName, 'r')
        self.soundBytes = self.wf.readframes(-1)
        self.timeAmplitudeArray = self.__calcTimeAmplitudeArray()


     def __calcTimeAmplitudeArray(self):
         self.internalTimeAmpList = [] # zero out the internal representation

         byteList = self.soundBytes
         if((byteList[i+1] & 0x080) == 0):
             amp = (byteList[i] & 0x0FF) + byteList[i+1] << 8
             #more code continues.....

错误:

if((int(byteList[i+1]) & 0x080) == 0):
TypeError: unsupported operand type(s) for &: 'str' and 'int'

我尝试过使用int()转换为整数类型,但没有成功。我有 Java 背景,这可以使用 byte 类型来完成,但这似乎不是 Python 的语言功能。任何方向将不胜感激。

最佳答案

您的问题来自这样一个事实:wave 库只是为您提供原始二进制数据(以字符串的形式)。

您可能需要使用 self.wf.getparams() 检查数据的形式。这将返回 (nchannels, sampwidth, framerate, nframes, comptype, compname) 。如果您确实有 1 个 channel 、样本宽度为 2 并且没有压缩(相当常见的波形类型),则可以使用以下命令(将 numpy 导入为 np)来获取数据:

byteList = np.fromstring(self.soundBytes,'<h')

这将返回一个包含数据的 numpy 数组。你不需要循环。如果您有不同的样本宽度,则第二个参数将需要不同的内容。我已经用简单的 .wav 进行了测试文件和 plot(byteList); show() (iPython 中的 pylab 模式)有效。

参见Reading *.wav files in Python其他方法可以做到这一点。

Numpyless 版本

如果你需要避免 numpy,你可以这样做:

import array
bytelist = array.array('h')
byteList.fromstring(self.soundBytes)

这和以前一样工作(用 plot(byteList); show() 测试)。 'h' 表示短签名。 len等作品。这确实会一次性导入 wav 文件,但 .wav 通常很小。并非总是如此。

关于Python Wave 库字符串到字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16655881/

相关文章:

Python:通过键获取字典中的值并用它们创建数组

python - 向路径添加变量

api - IBM Speech中的curl “Unsupported Media Type”错误

c++ - 如何减少或消除通过更改 16 位 PCM 样本的 'volume' 所产生的噪音

audio - ffmpeg : how to take wav as audio input for creating a video?

python - 如何获取 Qt QListWidget 中列出的选中项目

python - python 诅咒中的进度条

python - Google Oauth2 中的 400 错误请求访问 token

python - 如何使用 Python Selenium 在文本框(输入)中定位和插入值?

linux - 使 Python 文本变绿并使用旋转光标 - 新手问题