gpt4 book ai didi

python - 在python中连接合成音调

转载 作者:太空狗 更新时间:2023-10-30 03:06:03 25 4
gpt4 key购买 nike

我正在使用以下代码生成一个 wav 文件,其中包含持续 2 秒的 440 Hz 音调。

from scipy.io.wavfile import write
from numpy import linspace,sin,pi,int16

def note(freq, len, amp=1, rate=44100):
t = linspace(0,len,len*rate)
data = sin(2*pi*freq*t)*amp
return data.astype(int16) # two byte integers

tone = note(440,2,amp=10000)

write('440hzAtone.wav',44100,tone) # writing the sound to a file

我想知道我是否可以修改代码,以 note 方法为基础,以便用 python 实际生成一首曲子。

我尝试添加两种不同的音调,正如预期的那样,这两种音调同时播放,产生了听起来有点像拨号音的声音:

tone1 = note(440,2,amp=10000)
tone2 = note(480,2,amp=10000)
tone = tone1+tone2

write('440hzAtone.wav',44100,tone)

我也试过将两种音调相乘,但这只会产生静电。

我还尝试生成不同长度的音调并添加它们,但是这会引发异常,如下所示:

tone1 = note(440,2,amp=10000)
tone2 = note(480,1,amp=10000)
tone = tone1+tone2

write('440hzAtone.wav',44100,tone)

原因:

ValueError: operands could not be broadcast together with shapes (88200) (44100)

所以,我想知道 - 我怎样才能像这样连接不同的音调来创作曲子?

最佳答案

您可以使用 numpy.concatenate 执行此操作(已发布)。您还需要指定串联轴。用很低的速率来说明:

from scipy.io.wavfile import write
from numpy import linspace,sin,pi,int16,concatenate

def note(freq, len, amp=1, rate=5):
t = linspace(0,len,len*rate)
data = sin(2*pi*freq*t)*amp
return data.astype(int16) # two byte integers

tone1 = note(440,2,amp=10)
tone2 = note(140,2,amp=10)
print tone1
print tone2
print concatenate((tone2,tone1),axis=1)

#output:
[ 0 -9 -3 8 6 -6 -8 3 9 0]
[ 0 6 9 8 3 -3 -8 -9 -6 0]
[ 0 6 9 8 3 -3 -8 -9 -6 0 0 -9 -3 8 6 -6 -8 3 9 0]

关于python - 在python中连接合成音调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9794616/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com