4

我正在使用以下代码,它将生成一个 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)

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

4

2 回答 2

4

您可以使用 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]
于 2012-03-20T21:10:56.933 回答
0

numpy.linspace创建一个 numpy 数组。要连接音调,您需要连接相应的数组。为此,谷歌搜索表明 Numpy 提供了有用的命名numpy.concatenate函数

于 2012-03-20T20:57:59.683 回答