简体   繁体   English

在numpy中的两个频率之间进行插值

[英]Interpolating between two frequencies in numpy

I want to create a sine wave that starts from the frequency f1 and ends at the frequency f2. 我想创建一个从频率f1开始到频率f2结束的正弦波。 Here is the code I used: 这是我使用的代码:

import matplotlib.pyplot as plt
import numpy as np

def freq_interp(dur,f1,f2,fs=44100):
    num_samples = fs*dur
    t = np.linspace(0,dur,num_samples)
    a = np.linspace(0,1,num_samples)
    f = (1-a)*f1+a*f2 # interpolate
    samples = np.cos(2*np.pi*f*t)
    return samples,f

When I try to generate a WAV file or just plot the STFT of the signal, I get an unexpected result. 当我尝试生成WAV文件或仅绘制信号的STFT时,会得到意外的结果。 For example I used the code below: 例如,我使用下面的代码:

def plot_stft(sig,fs=44100):
    f, t, Zxx = signal.stft(sig,fs=fs,nperseg=2000)
    plt.pcolormesh(t, f, np.abs(Zxx), vmin=0, vmax=0.1)
    plt.ylim(0,2000)
    plt.title('STFT Magnitude')
    plt.ylabel('Frequency [Hz]')
    plt.xlabel('Time [sec]')
    plt.show()

s,f = freq_interp(dur=2,f1=1,f2=1000)
plt.plot(f)
plt.show()
plot_stft(s)

s,f = freq_interp(dur=2,f1=1000,f2=1)
plt.plot(f)
plt.show()
plot_stft(s)

I get these plots: 我得到这些情节: 在此处输入图片说明

The problem is more evident in the second row. 该问题在第二行中更加明显。 Where the frequency has bounced back at t=1s. 频率在t = 1s处反弹。 Also in the first row you can see that the frequency has gone up to 2000Hz which is wrong. 同样在第一行中,您可以看到频率上升到2000Hz,这是错误的。 Any idea why this happens and how I can fix it? 知道为什么会发生这种情况以及如何解决吗?

A sin wave is sin(p(t)) where p(t) is the phase function. 正弦波是sin(p(t)),其中p(t)是相位函数。 And frequency function is f(t) = dp(t) / dt, to calculate p(t), you first calculate f(t) and then integrate it. 频率函数为f(t)= dp(t)/ dt,要计算p(t),首先要计算f(t),然后对其进行积分。 The simplest method of integration is by using cumsum() . 最简单的集成方法是使用cumsum()

def freq_interp(dur,f1,f2,fs=44100):
    num_samples = int(fs*dur)
    t = np.linspace(0,dur,num_samples)
    f = np.linspace(f1, f2, num_samples)
    phase = 2 * np.pi * np.cumsum(f) / fs
    samples = np.cos(phase)
    return t, samples

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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