我正在编写一个Python程序,以不同的开始和结束频率以及不同的时间间隔一个接一个地生成多个正弦扫描。
一个例子是:
因此应该是一个上升,下降波形。
我使用的方程式受this thread启发
def LinearSineSweep(self, fStart, fEnd, samplingTime, samplesPerSecond):
nValues = int(samplesPerSecond * samplingTime)
for i in range(0, nValues):
delta = float(i) / nValues
t = samplingTime * delta
phase = 2 * math.pi * t * (fStart + (fEnd - fStart) * delta / 2)
return self._amplitude * math.sin(phase) + self._dcOffset
LinearSineSweep(0, 170, 0.001, 44100)
LinearSineSweep(170, 170, 0.001, 44100)
LinearSineSweep(170, 10, 0.001, 44100)
但是我得到的输出不正确:
即使是10倍的频率,也仍然不能作为一个波形合并在一起
这是数学问题还是编程问题?
最佳答案
正如@jaket在评论中指出的那样,您必须使每个阶段的相位连续变化(我在解释一下)。这是代码的一种变体,显示了可以执行此操作的一种方法。我没有您所有的其他代码,因此self
的第一个参数不是LinearSineSweep
,而是一个文件,样本以文本形式写入其中。 (我还对代码进行了调整,以补偿以下事实:请求的间隔通常不会是采样周期的精确倍数。)numpy
和matplotlib
用于创建图。
from __future__ import print_function, division
import math
def LinearSineSweep(f, fStart, fEnd, samplingTime, samplesPerSecond,
t0=0, phi0=0):
nValues = int(samplesPerSecond * samplingTime)
actualSamplingTime = nValues / samplesPerSecond
for i in range(0, nValues):
delta = float(i) / nValues
t = actualSamplingTime * delta
phase = 2 * math.pi * t * (fStart + (fEnd - fStart) * delta / 2)
value = math.sin(phase + phi0)
# Write the time and sample value to the output...
print(t0 + t, value, file=f)
phase = 2 * math.pi * actualSamplingTime * (fStart + (fEnd - fStart) / 2)
return t0 + actualSamplingTime, phi0 + phase
if __name__ == "__main__":
with open('out.csv', 'w') as f:
t, phi = LinearSineSweep(f, 0, 1700, 0.001, 44100)
t, phi = LinearSineSweep(f, 1700, 1700, 0.001, 44100, t, phi)
t, phi = LinearSineSweep(f, 1700, 100, 0.001, 44100, t, phi)
import numpy as np
import matplotlib.pyplot as plt
tvals, v = np.loadtxt('out.csv', unpack=True)
plt.figure(figsize=(10, 4))
plt.plot(tvals, v)
plt.grid()
plt.show()
这是情节:
关于python - 一个接一个地计算多个正弦波,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33121060/