wav.py 文件源码

python
阅读 34 收藏 0 点赞 0 评论 0

项目:mirapie 作者: Chutlhu 项目源码 文件源码
def wavread(fileName, lmax=np.infty, offset = 0, len_in_smpl = False):
    """reads the wave file file and returns a NDarray and the sampling frequency"""

    def isValid(filename):
        if not fileName:
            return False
        try:
            fileHandle = wave.open(fileName, 'r')
            fileHandle.close()
            return True
        except:
            return False
    if not isValid(fileName):
        print("invalid WAV file. Aborting")
        return None

    # metadata properties of a file
    length, nChans, fs, sampleWidth = wavinfo(fileName)
    if not len_in_smpl:
        lmax = lmax * fs
    length = min(length - offset, lmax)
    waveform = np.zeros((length, nChans))

    # reading data
    fileHandle = wave.open(fileName, 'r')
    fileHandle.setpos(offset)
    batchSizeT = 3000000
    pos = 0
    while pos < length:
        batchSize = min(batchSizeT, length - pos)
        str_bytestream = fileHandle.readframes(int(batchSize*2/sampleWidth))
        tempData = np.fromstring(str_bytestream, 'h')
        tempData = tempData.astype(float)
        tempData = tempData.reshape(batchSize, nChans)
        waveform[pos:pos+batchSize, :] = tempData / float(2**(8*sampleWidth - 1))
        pos += batchSize
    fileHandle.close()
    return (waveform, fs)
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号