Search code examples
pythonpython-3.xaudioscipyfrequency

Python: Calculating frequency over time from a wav file in Python?


I am using scipy's wavfile library to read a wavfile.

rate, data = scipy.io.wavfile.read(filename)

This will return the rate and RAW data of the given wav filename.

What transformation on the data array do I need to do to go from RAW data to frequency?

I understand FFT is used to go to the frequency domain, but I would like to go to the time domain.

Any help is appreciated! :)


Solution

  • This will give you the mean frequency over given signal:

    def spectral_statistics(y: np.ndarray, fs: int) -> float:
        """
        Compute mean frequency
    
        :param y: 1-d signal
        :param fs: sampling frequency [Hz]
        :return: mean frequency
        """
        spec = np.abs(np.fft.rfft(y))
        freq = np.fft.rfftfreq(len(y), d=1/fs)    
        amp = spec / spec.sum()
        mean = (freq * amp).sum()
        return mean 
    

    As you have said, you can read the wave with scipy. If you'd like to get frequencies for chunks of audio, simply split your array into pieces and pass each separately to the function.