def play_notes(self, notes=None):
if not notes:
notes = self.notes
player = pyaudio.PyAudio()
lib = sound_lib.SoundLib()
fs = 44100 # sampling rate, Hz, must be integer
stream = player.open(format=pyaudio.paFloat32,
channels=1,
rate=fs,
output=True)
old = 0
final = np.array([], dtype=np.float32)
for note in notes:
time.sleep(note[4]-old)
duration = note[5] # in seconds, may be float
f = lib.midi_to_freq(note[3]) # sine frequency, Hz, may be float
samples = (np.sin(2 * np.pi * np.arange(fs * duration) * f / fs)).astype(np.float32)
n = len(samples)
level = (note[6])/100
volume = [level]*n # range [0.0, 1.0]
volume[0] = 0
for index in range(1,n):
volume[index] = (-(2*((index/n)-0.5))**6 + 1)*volume[index]
samples[index] = samples[index]*volume[index]
old = note[4] + duration
final = np.append(final,samples)
stream.write(final,num_frames=len(final))
stream.stop_stream()
stream.close()
player.terminate()
#Play notes in a new thread instead of in the main thread.
评论列表
文章目录