我有一个.wav文件,采样率为44.1khz,我想使用librosa.resample将其重新采样为16khz。尽管output.wav听起来很棒,并且是16khz,但是当我尝试通过wave.open读取它时出现了错误。
并且这个问题与我的非常相似:Opening a wave file in python: unknown format: 49. What's going wrong?
这是我的代码:
if __name__ == "__main__":
input_wav = '1d13eeb2febdb5fc41d3aa7db311fa33.wav'
output_wav = 'result.wav'
y, sr = librosa.load(input_wav, sr=None)
print(sr)
y = librosa.resample(y, orig_sr=sr, target_sr=16000)
librosa.output.write_wav(output_wav, y, sr=16000)
wave.open(output_wav)
并且在最后一步wave.open(output_wav)
中出现错误
以下是例外:
Traceback (most recent call last):
File "/Users/range/Code/PycharmProjects/Speaker/test.py", line 204, in <module>
wave.open(output_wav)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/wave.py", line 499, in open
return Wave_read(f)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/wave.py", line 163, in __init__
self.initfp(f)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/wave.py", line 143, in initfp
self._read_fmt_chunk(chunk)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/wave.py", line 260, in _read_fmt_chunk
raise Error('unknown format: %r' % (wFormatTag,))
wave.Error: unknown format: 3
我只是不知道为什么不能wave.open读取wav_flie,因此我必须重新采样wav才能做进一步的工作。
我想知道librosa.output.write
是否更改了波形的类型。
所以我必须自己编写重采样函数。幸运的是,它有效。这是我的代码:
def resample(input_wav, output_wav, tar_fs=16000):
audio_file = wave.open(input_wav, 'rb')
audio_data = audio_file.readframes(audio_file.getnframes())
audio_data_short = np.fromstring(audio_data, np.short)
src_fs = audio_file.getframerate()
dtype = audio_data_short.dtype
audio_len = len(audio_data_short)
audio_time_max = 1.0*(audio_len-1) / src_fs
src_time = 1.0 * np.linspace(0, audio_len, audio_len) / src_fs
tar_time = 1.0 * np.linspace(0, np.int(audio_time_max*tar_fs), np.int(audio_time_max*tar_fs)) / tar_fs
output_signal = np.interp(tar_time, src_time, audio_data_short).astype(dtype)
with wave.open(output_wav, 'wb') as f:
f.setnchannels(1)
f.setsampwidth(2)
f.setframerate(tar_fs)
f.writeframes(output_signal)
我希望您能帮助我理解librosa对wav进行重采样时出了什么问题,我很高兴看到我的代码可以帮助其他遇到相同问题的人。 :)
我正在一个项目上,并且遇到了相同的错误,所以稍加挖掘,发现问题是由于librosa在输出模块中使用write_wav()写入wave文件的默认方式引起的。