Python Wave Library字符串到字节

2024-09-27 21:22:44 发布

您现在位置:Python中文网/ 问答频道 /正文

所以基本上,我试着读入wave文件的信息,这样我就可以获取字节信息并创建一个时间-振幅点数组。在

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.....

错误:

^{pr2}$

我尝试过使用int()来转换为整数类型,但是没有用。我来自一个Java背景,在那里可以使用byte类型来完成这项工作,但这似乎不是Python的语言特性。任何方向都将不胜感激。在


Tags: 文件theself信息类型字节def时间
2条回答

我通常使用array-modulefromstring方法。在

我对数据块进行操作的标准模式是:

def bytesfromfile(f):
    while True:
        raw = array.array('B')
        raw.fromstring(f.read(8192))
        if not raw:
            break
        yield raw

with open(f_in, 'rb') as fd_in:
    for byte in bytesfromfile(fd_in):
        # do stuff

上面的'B'表示无符号字符,即1字节。在

如果文件不是很大,那么您可以直接删除它:

^{pr2}$

Guido can't be wrong。。。在

如果您更喜欢numpy,我倾向于使用:

    fd_i = open(file.bin, 'rb')
    fd_o = open(out.bin, 'wb')

    while True:
        # Read as uint8
        chunk = np.fromfile(fd_i, dtype=np.uint8, count=8192)
        # use int for calculations since uint wraps
        chunk = chunk.astype(np.int)
        if not chunk.any():
            break
        # do some calculations
        data = ...

        # convert back to uint8 prior to writing.
        data = data.astype(np.uint8)
        data.tofile(fd_o)

    fd_i.close()
    fd_o.close()

或者阅读整个文件:

In [18]: import numpy as np

In [19]: f = open('foreman_cif_frame_0.yuv', 'rb')

In [20]: data = np.fromfile(f, dtype=np.uint8)

In [21]: data[0:10]
Out[21]: array([ 10,  40, 201, 255, 247, 254, 254, 254, 254, 254], dtype=uint8)

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

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

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

这将返回一个包含数据的numpy数组。你不需要循环。如果你有一个不同的样本宽度,在第二个参数中需要一些不同的东西。我用一个简单的.wav文件进行了测试,plot(byteList); show()(iPython中的pylab模式)可以工作。在

请参阅Reading *.wav files in Python以获取执行此操作的其他方法。在

无核版本

如果您需要避免numpy,您可以:

^{pr2}$

这和以前一样(用plot(byteList); show()测试)h'表示短签名。len等工作。这确实是一次导入所有的wav文件,但又是一次。wav通常很小。不总是这样。在

相关问题 更多 >

    热门问题