2012-03-20 60 views
4

我正在使用下面的代码,它将生成一个包含440赫兹持续2秒钟音调的wav文件。在python中连接合成音调

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 

我想知道如果我可以修改代码,基于它的注释方法,以便实际上生成与python曲调。

我尝试添加两种不同的音色,并如期两个音同时播放,创造一些东西,听起来有点像拨号音:

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

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

我也试过两个音调相乘,但这只是产生静态的。

我也试过genreating不同长度的色调并加入他们,但是这将导致一个异常要提高,像这样:

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

您可以使用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] 
+0

伟大的答案 - 谢谢 – 2012-03-20 21:16:13

0

numpy.linspace创建一个numpy数组。要连接音调,你需要连接相应的数组。为此,Google的一些信息表明Numpy提供了有用的名称numpy.concatenate function

+0

感谢,但如果我尝试'音=串连(TONE1,tone2)'我得到'类型错误:只有长度为1的阵列可以转换到Python scalars'? – 2012-03-20 21:02:51