Question

I'm using the following code which will generate a wav file which contains a tone at 440 Hz 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 could modify the code, basing it off the note method, in order to actually generate a tune with python.

I tried adding two different tones, and as expected the two tones play simultaneously, creating something which sounds a bit like a dial tone:

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

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

I also tried multiplying the two tones, but this just generates static.

I also tried genreating tones of different lengths and adding them, however this causes an exception to be raised, like so:

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 tones like this to make a tune?

Was it helpful?

Solution

You can do this using numpy.concatenate, (as already posted). You need to specify the concatenation axis also. Using very low rate 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]

OTHER TIPS

numpy.linspace creates a numpy array. To concatenate the tones, you'd want to concatenate the corresponding arrays. For this, a bit of Googling indicates that Numpy provides the helpfully named numpy.concatenate function.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top