wave write 函数不起作用,我做错了什么?

wave write function not working, what am I doing wrong?

我正在尝试将充满 .wav 文件的文件夹的现有采样率减半。这是我发现的唯一方法,但它不起作用。读取部分在 f.close() 之前工作正常,然后 wave.write 部分导致错误。

import wave
import contextlib
import os

for file_name in os.listdir(os.getcwd()):
    if file_name.endswith(".wav"):
        with contextlib.closing(wave.open(file_name, 'rb')) as f:
            rate = f.getframerate()
            new_rate = rate/2
            f.close()
            with contextlib.closing(wave.open(file_name, 'wb')) as f:
                rate = f.setframerate(new_rate)

这是我运行时的输出。

Traceback (most recent call last):
  File "C:\Users\hsash\OneDrive\Desktop\used AR1-20210513T223533Z-001 - Copy (2)\sounds\python code.py", line 36, in <module>
    rate = f.setframerate(new_rate)
  File "C:\Users\hsash\AppData\Local\Programs\Python\Python39\lib\contextlib.py", line 303, in __exit__
    self.thing.close()
  File "C:\Users\hsash\AppData\Local\Programs\Python\Python39\lib\wave.py", line 444, in close
    self._ensure_header_written(0)
  File "C:\Users\hsash\AppData\Local\Programs\Python\Python39\lib\wave.py", line 462, in _ensure_header_written
    raise Error('# channels not specified')
wave.Error: # channels not specified

上面写着#channels not specified。当您打开一个 wavefile 进行写入时,python 将所有 header 字段设置为零,而不管文件的当前状态如何。

为了确保保存其他字段,您需要在第一次阅读旧文件时将它们复制过来。

在下面的代码片段中,我使用 getparamssetparams 复制 header 字段,我使用 readframeswriteframes复制波形数据。

import wave
import contextlib
import os

for file_name in os.listdir(os.getcwd()):
    if file_name.endswith(".wav"):
        with contextlib.closing(wave.open(file_name, 'rb')) as f:
            rate = f.getframerate()
            params = f.getparams()

            frames = f.getnframes()
            data = f.readframes(frames)


            new_rate = rate/2
            f.close()
            with contextlib.closing(wave.open(file_name, 'wb')) as f:
                f.setparams(params)
                f.setframerate(new_rate)
                f.writeframes(data)