Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read a .wav file using SciPy at a different sampling rate?

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?

like image 710
user2539621 Avatar asked Nov 12 '15 22:11

user2539621


1 Answers

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.

like image 60
Frank Zalkow Avatar answered Oct 20 '22 00:10

Frank Zalkow