简体   繁体   English

如何使用 Python 生成正弦波?

[英]How do I generate a sine wave using Python?

I'm trying to generate a sine wave of a given frequency for a given duration and then write it into a.wav file.我试图在给定的持续时间内生成给定频率的正弦波,然后将其写入 a.wav 文件。 I'm using numpy's sin function and scipy's wavfile function. I'm getting a weird sound that is definitely not a sine wave.我正在使用 numpy 的 sin function 和 scipy 的 wavfile function。我听到一种奇怪的声音,这绝对不是正弦波。

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)

Any help would be appreciated.任何帮助,将不胜感激。 Have I made some fundamentally incorrect assumption about sine waves or something?我对正弦波或其他东西做了一些根本上不正确的假设吗?

Use this and set the parameters as you want使用它并根据需要设置参数

start_time = 0
end_time = 1
sample_rate = 1000
time = np.arange(start_time, end_time, 1/sample_rate)
theta = 0
frequency = 100
amplitude = 1
sinewave = amplitude * np.sin(2 * np.pi * frequency * time + theta)
figure(figsize=(20, 6), dpi=80)
plt.plot(sinewave)

A simplified approach:一种简化的方法:

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))

Generates:生成:

[ 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]

生成的正弦波


Note: Leaving this answer here despite not addressing sine wave for audio generation, since I found that for my application it was more intuitive to only parameterise length of the wave and number of datapoints generated, as opposed to fundamental frequency and duration in seconds.注意:尽管没有解决音频生成的正弦波问题,但仍将此答案留在这里,因为我发现对于我的应用程序,仅参数化波的长度和生成的数据点数量更为直观,而不是基频和以秒为单位的持续时间。

Change 更改

samples = np.arange(t * fs)

to

samples = np.linspace(0, t, int(fs*t), endpoint=False)

(This assumes that fs*t results in an integer value.) (这假设fs*t产生整数值。)

Or, as Paul Panzer suggests in a comment, 或者,正如Paul Panzer在评论中所说,

samples = np.arange(t * fs) / fs

Your samples was just the sequence of integers 0, 1, 2, ... fs*t . 你的samples只是整数0,1,2,... fs*t的序列。 Instead, you need the actual time values (in seconds) of the samples. 相反,您需要样本的实际时间值(以秒为单位)。

You are mixing sample value and length! 您正在混合样本值和长度! Try: 尝试:

samples = np.linspace(0, t, t * fs)

Another detail: you don't need the str around raw_input . 另一个细节:你不需要str周围raw_input

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

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