How it works...

The initial lines of code import the necessary libraries and set up the constants that are required for the rest of the code in the program. The MELODY constant has the sequence of notes that make up the song. There are pauses of silence between certain notes; these are simply specified with a value of 0 to indicate that no notes should be played at this point. The play_note function expects to be given the frequency of the note to play and, optionally, the duration of time to play the note for. If a frequency of 0 is given, it will call the sleep function to stay silent; otherwise, it will play the note as a tone.

Finally, the for loop at the end of the program simply loops through each note defined in the melody and plays it by calling the play_note function. In this way, you can define many different melodies and songs, and play different songs depending on how the user interacts with the device.