Bad*_*han 6 python trigonometry waveform numpy scipy
我正在尝试在给定的持续时间内生成给定频率的正弦波,然后将其写入 .wav 文件。我正在使用 numpy 的 sin 函数和 scipy 的 wavfile 函数。我听到一种奇怪的声音,这绝对不是正弦波。
import numpy as np
from scipy.io import wavfile
fs = 44100
f = int(raw_input("Enter fundamental frequency: "))
t = float(raw_input("Enter duration of signal (in seconds): "))
samples = np.arange(t * fs)
signal = np.sin(2 * np.pi * f * samples)
signal *= 32767
signal = np.int16(signal)
wavfile.write(str(raw_input("Name your audio: ")), fs, signal)
Run Code Online (Sandbox Code Playgroud)
任何帮助,将不胜感激。我是否对正弦波或其他东西做出了一些根本不正确的假设?
改变
samples = np.arange(t * fs)
Run Code Online (Sandbox Code Playgroud)
到
samples = np.linspace(0, t, int(fs*t), endpoint=False)
Run Code Online (Sandbox Code Playgroud)
(这假设fs*t结果为整数值。)
或者,正如 Paul Panzer 在评论中所建议的那样,
samples = np.arange(t * fs) / fs
Run Code Online (Sandbox Code Playgroud)
你samples只是整数序列 0, 1, 2, ... fs*t。相反,您需要样本的实际时间值(以秒为单位)。
一个简化的方法:
cycles = 2 # how many sine cycles
resolution = 25 # how many datapoints to generate
length = np.pi * 2 * cycles
my_wave = np.sin(np.arange(0, length, length / resolution))
Run Code Online (Sandbox Code Playgroud)
生成:
[ 0. 0.4818 0.8443 0.998 0.9048 0.5878 0.1253 -0.3681 -0.7705
-0.9823 -0.9511 -0.6845 -0.2487 0.2487 0.6845 0.9511 0.9823 0.7705
0.3681 -0.1253 -0.5878 -0.9048 -0.998 -0.8443 -0.4818]
Run Code Online (Sandbox Code Playgroud)
注意:尽管没有解决音频生成的正弦波问题,但仍将这个答案留在这里,因为我发现对于我的应用程序来说,仅参数化波的长度和生成的数据点的数量更直观,而不是基频和以秒为单位的持续时间。
| 归档时间: |
|
| 查看次数: |
20676 次 |
| 最近记录: |