如何使用SciPy以不同的采样率读取.wav文件?

时间:2015-11-12 22:18:13

标签: python audio scipy

默认情况下,scipy.io.wavfile.read每秒采样44100个样本。是否可以更改此值,让它每秒钟吸取少量样本?

1 个答案:

答案 0 :(得分:4)

scipy.io.wavfile.read的第一个返回值是samplerate,它取自音频文件的标题。如果您想更改采样率,则必须执行一些samplerate rate conversion

这里有一些通过插值更改采样率的基本代码。请注意,如果原始采样率低于新采样率,则这只是无害的。反过来说,如果音频文件包含的频率高于Nyquist frequency,则可能会引入别名。如果是这种情况,则应在插值前应用滤镜。

import numpy as np
from scipy.io import wavfile
from scipy import interpolate

NEW_SAMPLERATE = 48000

old_samplerate, old_audio = wavfile.read("test.wav")

if old_samplerate != NEW_SAMPLERATE:
    duration = old_audio.shape[0] / old_samplerate

    time_old  = np.linspace(0, duration, old_audio.shape[0])
    time_new  = np.linspace(0, duration, int(old_audio.shape[0] * NEW_SAMPLERATE / old_samplerate))

    interpolator = interpolate.interp1d(time_old, old_audio.T)
    new_audio = interpolator(time_new).T

    wavfile.write("out.wav", NEW_SAMPLERATE, np.round(new_audio).astype(old_audio.dtype))