Concatenating synthesized tones in python

I am using the following code that will generate a wav file that contains a 440 Hz tone, lasting for 2 seconds.

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 

I was wondering if I can change the code based on the annotation method to actually generate the melody using python.

I tried adding two different tones, and, as expected, two tones play simultaneously, creating something similar to a beep:

 tone1 = note(440,2,amp=10000) tone2 = note(480,2,amp=10000) tone = tone1+tone2 write('440hzAtone.wav',44100,tone) 

I also tried multiplying two tones, but it just creates static.

I also tried playing tones of different lengths and adding them, however this throws an exception, for example:

 tone1 = note(440,2,amp=10000) tone2 = note(480,1,amp=10000) tone = tone1+tone2 write('440hzAtone.wav',44100,tone) 

causes:

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

So, I was wondering - how can I concatenate different melodies like this to make a melody?

+4
source share
2 answers

You can do this with numpy.concatenate (as already published). You also need to specify the concatenation axis. Using a very low speed to illustrate:

 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] 
+4
source

numpy.linspace creates an numpy array. To concatenate tones, you want to combine the corresponding arrays. To this end, a little Googling indicates that Numpy provides a service called numpy.concatenate .

0
source

Source: https://habr.com/ru/post/1402535/


All Articles