12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788 |
- import numpy as np
- import pyaudio
- from numpy import linspace, sin, pi, int16
- import pylab as plt
- from scipy import signal
- def callback(in_data, frame_count, time_info, status):
- # data = wf.readframes(frame_count)
- global freq, length
- # freq = 300
- data = note(freq, length, amp=amp, rate=RATE)
- return (data, pyaudio.paContinue)
- def note(freq, t_len, amp=1, rate=44100, mode='sin'):
- n_sample = int(t_len * rate)
- factor = (float(freq) * np.pi * 2 / rate)
- data = []
- if mode == 'saw':
- data = signal.sawtooth(np.arange(n_sample) * factor, .25) * amp
- else:
- data = np.sin(np.arange(n_sample) * factor) * amp
- fade = int(n_sample/5)
- fade_in = np.arange(0., 1., 1/fade)
- fade_out = np.arange(1., 0., -1/fade)
- data[:fade] = np.multiply(data[:fade], fade_in)
- data[-fade:] = np.multiply(data[-fade:], fade_out)
- return data.astype(np.float32)
- RATE = 44100
- # RATE = 1000
- FREQ = 262
- freq = 440
- length = 0.5*freq/1000.
- amp = 10000
- pa = pyaudio.PyAudio()
- s = pa.open(output=True,
- channels=2,
- rate=RATE,
- format=pyaudio.paFloat32)
- # stream_callback=callback)
-
- freqs = [440, 50, 100, 200, 300, 230, 120, 500, 40, 125]
- # while freq<400:
- for ii in range(len(freqs)):
- length = .5# 200/ freq
- # length = 1.
-
- # freq = np.random.randint(50,250)
- freq = freqs[ii]
- print(ii, freq, length)
-
-
- tone = note(freq, length, amp=1, rate=RATE, mode='saw')
- print(f'tone length: {len(tone)}, in seconds: {len(tone)/2 / RATE}')
- tone = np.repeat(tone.reshape((-1, 1)), 2, axis=1).flatten() # need to copy, because we have 2 channels
-
- print(f'tg: {tone}, {np.min(tone)}, {np.max(tone)}, {np.amin(tone)}, {np.amax(tone)}')
- s.write(tone.tostring())
-
- # freq += 10
- # freq = np.random.randint(50,250)
- # amp = freq*20
- # freq += 10
- # time.sleep(length)
- # time.sleep(10)
- tone0 = tone
- dd = np.hstack((tone0, tone))
- plt.figure(1)
- plt.clf()
- xx1 = range(len(tone0))
- xx2 = range(xx1[-1], xx1[-1] + len(tone))
- plt.plot(xx1, tone0, 'b-o')
- plt.plot(xx2, tone, 'r-o')
- plt.show()
- s.stop_stream()
- s.close()
- # pa.terminate()​
|