将数据附加到波形声音文件而不加载其当前内容

Man*_*ira 5 python audio wave

我正在尝试将数据附加到声音文件而不加载其内容(因为它可能有千兆字节的数据),我目前正在使用 pysoundfile 库,我已经找到了一种方法来为 wave64 做到这一点,但是在 wav 中,由于某种原因它抛出一个错误。

根据 pysoundfile 文档,当使用文件描述符打开 SoundFile 时,它​​应该在不截断的情况下写入,所以这就是我当前正在做的事情

    fd = open('foo.wav',mode='ab')
    with sf.SoundFile(fd, mode = 'w', samplerate = self._samplerate,channels = self._channels, format = 'wav') as wfile:
        wfile.seek(0,sf.SEEK_END)
        wfile.write(self._samples)
        wfile.close()
    fd.close()
Run Code Online (Sandbox Code Playgroud)

当我使用 Wave 文件类型时,出现以下错误:

RuntimeError: Error opening <_io.BufferedWriter name='../datasets/emddf_clean/qcoisa.wav'>: Unspecified internal error.
Run Code Online (Sandbox Code Playgroud)

但是对于 w64 格式的文件来说,它可以以某种方式工作...如果有人可以阐明我,那将是惊人的,提前致谢!

Man*_*ira 3

我成功地做到了我想要的,没有显式使用文件描述符:

    with sf.SoundFile(path['full_path'], mode = 'r+') as wfile:
        wfile.seek(0,sf.SEEK_END)
        wfile.write(self._samples)
Run Code Online (Sandbox Code Playgroud)

如果文件处于r+模式(读/写),它支持查找,这意味着我们可以指向文件的末尾以允许追加。唯一的问题是,如果该文件尚不存在,则会抛出错误,但您可以通过执行以下操作轻松修复它:

    if(self.mode == my_utils.APPEND and os.path.isfile(path['full_path'])):
        with sf.SoundFile(path['full_path'], mode = 'r+', samplerate = samplerate) as wfile:
            wfile.seek(0,sf.SEEK_END)
            wfile.write(self.file.getSamples())
    else:
        sf.write(path['full_path'], self.file.getSamples(), samplerate,format=path['extension']) # writes to the new file 
    return
Run Code Online (Sandbox Code Playgroud)

希望我说得清楚并帮助别人!