Updating/appending to a .wav file in Python

[亡魂溺海] 提交于 2021-01-28 05:23:02

问题


I have a stream of PCM audio frames coming into my Python script, and I am able to save blocks of these frames as .wav files as such:

def update_wav():
    filename = "test.wav"
    wav_file = wave.open(filename, "wb")
    n_frames = len(audio)

    wav_file.setparams((n_channels, sample_width, sample_rate, n_frames, comptype, compname))
    for sample in audio:
        wav_file.writeframes(struct.pack('h', int(sample * 32767.0)))
    wav_file.close()

However, I'd like this to continually update as new frames come in. Is there way to writeframe in a way that appends to an existing .wav file? Right now I am only able to accomplish an overwrite.


回答1:


I found a way of doing this with SciPy, it actually seems to be the default functionality for their writing method.

import scipy.io.wavfile

def update_wav():
    numpy_data = numpy.array(audio, dtype=float)
    scipy.io.wavfile.write("test.wav", 8000, numpy_data)


来源:https://stackoverflow.com/questions/54936484/updating-appending-to-a-wav-file-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!