简体   繁体   中英

How to fit a sinusoidal graph to an audio signal in order to determine frequency and amplitude in Python?

I have an audio signal which has a form similar to the below. I have tried to use Scipy's optimise library to fit a sine function to the data however this does not seem to work due to the form of the data. How else could I fit a sine function to determine the frequency and amplitude?

There are many ways to extract this information out of the data. You can (and probably should) apply some spectral analysis for the most accurate results. Check out SciPy's spectrogram , for instance. However, to quickly get an estimate of the frequency, you could just look at the zero-crossings:

import numpy as np
import matplotlib.pyplot as plt
from math import pi

# Generate a 2 second array of data with millisecond resolution
time, timestep = np.linspace(0, 2, 2000, endpoint=False, retstep=True)
# Generate a constant frequency sine wave with varying amplitude
frequency = 42
amplitude = 1 / ((time - 1)**2 + 0.03)
data = amplitude * np.sin(2*pi*frequency*time)
plt.plot(time, data)

# Extract rising zero crossings
rising_zero_crossing_indices = np.where(np.diff(np.sign(data)) > 0)[0]
rising_zero_crossing_times = time[rising_zero_crossing_indices]

# Find the frequency 
period = np.diff(rising_zero_crossing_times)
avg_frequency = 1/np.mean(period)

print(avg_frequency)

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM