For the next part, we will need some helper functions that will allow us to use Python to synthesize a note. Fundamentally, a note is a wave (the type of wave will change how the note sounds to our ears, similar to the way the same note on different instruments sounds different) with a frequency (which produces the distinct note) and an amplitude (indicating its volume). Python has a variety of options for playing notes and chords, many of which involve a large package, a sound pack, and or/external installations. To avoid this, we used the pygame module together with a simple choice of wave (sine wave) to make a simple note synthesizer in just a few lines:
import numpy
import pygame, pygame.sndarray
import pickle
def play_notes(freqs,volumes):
"""
freqs: a list of frequencies in Hz
volumes a list of volumes: (1 highest 0 lowest)
example usage:
play_notes([440,880],[0.6,0.2])
"""
pygame.mixer.init()
sample_wave=sum([numpy.resize(volume*16384*numpy.sin(numpy.arange(int(44100/float(hz)))*numpy.pi*2/(44100/float(hz))),(44100,)).astype(numpy.int16) for hz,volume in zip(freqs,volumes)])
stereo = numpy.vstack((sample_wave, sample_wave)).T.copy(order='C')
sound = pygame.sndarray.make_sound(stereo)
sound.play(-1)
pygame.time.delay(1000)
sound.stop()
pygame.time.delay(1000)