By default, scipy.io.wavfile.read samples at 44100 samples per a second. Is it possible to change this value, to have it grab a smaller amount of samples per a second?
The first return value of scipy.io.wavfile.read
is the samplerate and it is taken from the header of the audio file. If you want to change the sample rate, you have to do some samplerate rate conversion.
Here some basic code to change the samplerate by interpolation. Note that this is only harmless, if the original sample rate is lower than the new one. The other way around, you could introduce aliasing if the audio file contains frequencies higher than the Nyquist frequency. If this is the case you should apply a filter before interpolating.
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))
EDIT: You may have a look at the Python package resampy
, which implements efficient sample rate conversion.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With