Python 用struct重建我的wave文件

Python 用struct重建我的wave文件,python,audio,struct,Python,Audio,Struct,我的目标是读取一个波形文件并编辑它的数据,方法是在-1到1的范围内为每个数据位添加一个随机数,希望产生一些失真,然后将其保存为一个编辑过的波形文件。我阅读并编辑wave文件,如下所示: riffTag = fileIn.read(4) if riffTag != 'RIFF': print 'not a valid RIFF file' exit(1) riffLength = struct.unpack('<L', fileIn.read(4))[0] riffType

我的目标是读取一个波形文件并编辑它的数据,方法是在-1到1的范围内为每个数据位添加一个随机数,希望产生一些失真,然后将其保存为一个编辑过的波形文件。我阅读并编辑wave文件,如下所示:

riffTag = fileIn.read(4)
if riffTag != 'RIFF':
    print 'not a valid RIFF file'
    exit(1)

riffLength = struct.unpack('<L', fileIn.read(4))[0]
riffType = fileIn.read(4)
if riffType != 'WAVE':
    print 'not a WAV file'
    exit(1)

# now read children
while fileIn.tell() < 8 + riffLength:
    tag = fileIn.read(4)
    length = struct.unpack('<L', fileIn.read(4))[0]

    if tag == 'fmt ':  # format element
        fmtData = fileIn.read(length)
        fmt, numChannels, sampleRate, byteRate, blockAlign, bitsPerSample = struct.unpack('<HHLLHH', fmtData)
        stHeaderFields['AudioFormat'] = fmt
        stHeaderFields['NumChannels'] = numChannels
        stHeaderFields['SampleRate'] = sampleRate
        stHeaderFields['ByteRate'] = byteRate
        stHeaderFields['BlockAlign'] = blockAlign
        stHeaderFields['BitsPerSample'] = bitsPerSample

    elif tag == 'data': # data element
        rawData = fileIn.read(length)

    else: # some other element, just skip it
        fileIn.seek(length, 1)

numChannels = stHeaderFields['NumChannels']

# some sanity checks
assert(stHeaderFields['BitsPerSample'] == 16)
assert(numChannels * stHeaderFields['BitsPerSample'] == blockAlign * 8)

samples = []
edited_samples = []

for offset in range(0, len(rawData), blockAlign):
    samples.append(struct.unpack('<h', rawData[offset:offset+blockAlign]))

for sample in samples:
    edited_samples.append(sample[0] + random.randint(-1, 1))
riffTag=fileIn.read(4)
如果riffTag!='里夫语:
打印“不是有效的RIFF文件”
出口(1)

riffLength=struct.unpack(“除非您出于其他原因(获得处理二进制文件的经验等)打算自己编写对.wav文件的支持,不要这样做。Python附带了处理所有文件格式问题的模块,让您只处理数据。

我很遗憾不能使用wave库,因为我的项目经理希望我以后扩展此项目,以处理类似于音频文件的ECG文件。遗憾的是,它必须使用二进制文件。啊,这很有意义。很确定标准库中没有这一点。:)
foo = []
for sample in edited_samples:
    foo.append(struct.pack('<h', int(sample)))

with open(fileIn.name + ' edited.wav', 'w') as file_out:
    file_out.write('RIFF')
    file_out.write(struct.pack('<L', riffLength))
    file_out.write('WAVE')
    file_out.write(ur'fmt\u0020')
    file_out.write(struct.pack('<H', fmt))
    file_out.write(struct.pack('<H', numChannels))
    file_out.write(struct.pack('<L', sampleRate))
    file_out.write(struct.pack('<L', byteRate))
    file_out.write(struct.pack('<H', blockAlign))
    file_out.write(struct.pack('<H', bitsPerSample))
    file_out.write('data')
    for item in foo:
        file_out.write(item)