简体   繁体   English

波浪写功能不起作用,我做错了什么?

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

I am trying to halve the existing sampling rate of a folder full of .wav files.我试图将一个充满 .wav 文件的文件夹的现有采样率减半。 This is the only way I have found to do it but it is not working.这是我发现的唯一方法,但它不起作用。 The read part works just fine up until f.close(), then the wave.write part causes the error.读取部分工作正常,直到 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)

This is the output when I run it.这是我运行时的输出。

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

It says right there that #channels not specified .它就在那里说#channels not specified When you are opening a wavefile for writing, python sets all of the header fields to zero irrespectively of the current state of the file.当您打开波形文件进行写入时,无论文件的当前状态如何,python 都会将所有标头字段设置为零。

In order to make sure that the other fields are saved you need to copy them over from the old file when you read it the first time.为了确保保存其他字段,您需要在第一次阅读时从旧文件中复制它们。

In the snippet below I'm using getparams and setparams to copy the header fields over and I'm using readframes and writeframes to copy the wave data.在下面的代码片段中,我使用getparamssetparams复制标题字段,并使用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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM