The Python Oracle

Audio Frequencies in Python

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Realization

--

Chapters
00:00 Question
01:48 Accepted answer (Score 16)
04:02 Thank you

--

Full question
https://stackoverflow.com/questions/5330...

Accepted answer links:
[matplotlib.pyplot.magnitude_spectrum]: https://matplotlib.org/3.1.1/api/_as_gen...
[image]: https://i.stack.imgur.com/cQadd.png
[image]: https://i.stack.imgur.com/cEJKa.png
[SciPy's Fourier Transforms]: https://docs.scipy.org/doc/scipy/referen...
[Matplotlib's magnitude spectrum plotting]: https://matplotlib.org/3.1.0/api/_as_gen...
[image]: https://i.stack.imgur.com/etuFr.png

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #numpy #audio #pyaudio #wave

#avk47



ACCEPTED ANSWER

Score 17


This function below finds the frequency spectrum. I have also included a sine signal and a WAV file sample application. This is for educational purposes; you may alternatively use the readily available matplotlib.pyplot.magnitude_spectrum (see below).

from scipy import fft, arange
import numpy as np
import matplotlib.pyplot as plt
from scipy.io import wavfile
import os


def frequency_spectrum(x, sf):
    """
    Derive frequency spectrum of a signal from time domain
    :param x: signal in the time domain
    :param sf: sampling frequency
    :returns frequencies and their content distribution
    """
    x = x - np.average(x)  # zero-centering

    n = len(x)
    k = arange(n)
    tarr = n / float(sf)
    frqarr = k / float(tarr)  # two sides frequency range

    frqarr = frqarr[range(n // 2)]  # one side frequency range

    x = fft(x) / n  # fft computing and normalization
    x = x[range(n // 2)]

    return frqarr, abs(x)


# Sine sample with a frequency of 1hz and add some noise
sr = 32  # sampling rate
y = np.linspace(0, 2*np.pi, sr)
y = np.tile(np.sin(y), 5)
y += np.random.normal(0, 1, y.shape)
t = np.arange(len(y)) / float(sr)

plt.subplot(2, 1, 1)
plt.plot(t, y)
plt.xlabel('t')
plt.ylabel('y')

frq, X = frequency_spectrum(y, sr)

plt.subplot(2, 1, 2)
plt.plot(frq, X, 'b')
plt.xlabel('Freq (Hz)')
plt.ylabel('|X(freq)|')
plt.tight_layout()


# wav sample from https://freewavesamples.com/files/Alesis-Sanctuary-QCard-Crickets.wav
here_path = os.path.dirname(os.path.realpath(__file__))
wav_file_name = 'Alesis-Sanctuary-QCard-Crickets.wav'
wave_file_path = os.path.join(here_path, wav_file_name)
sr, signal = wavfile.read(wave_file_path)

y = signal[:, 0]  # use the first channel (or take their average, alternatively)
t = np.arange(len(y)) / float(sr)

plt.figure()
plt.subplot(2, 1, 1)
plt.plot(t, y)
plt.xlabel('t')
plt.ylabel('y')

frq, X = frequency_spectrum(y, sr)

plt.subplot(2, 1, 2)
plt.plot(frq, X, 'b')
plt.xlabel('Freq (Hz)')
plt.ylabel('|X(freq)|')
plt.tight_layout()

plt.show()

Sine signal


WAV file

You may also refer to SciPy's Fourier Transforms and Matplotlib's magnitude spectrum plotting pages for extra reading and features.

magspec = plt.magnitude_spectrum(y, sr)  # returns a tuple with the frequencies and associated magnitudes

enter image description here