So now we know how to play a melody. For our Hot Potato game, we will want to let this melody play for a random amount of time and then stop it. How do we do that?

There is a very simple way we can do this. Instead of thinking in terms of time, just think in terms of number of notes. We'll just pick a random number of notes and play only that many.

Stop Melody 1

Here is a modified version of the previous program which only plays a random number of notes from the melody. It also moves the melody definition to a separate file called

Stop Melody 2

The one problem with the previous approach is it will play the melody at most only once. For our Hot Potato game, we may want the melody to play longer (multiple times) to make the game more exciting. So we want to be able to specify a random number bigger than the number of notes in the melody. Say the melody had 10 notes. A loop of 10 would play it once. But we want to be able to loop 20 times to play it twice. Or 17 times to play it once, and then the first 7 notes again. Etc.

But we can't simply increase the size of our random number and use the same loop structure. Once the loop number exceeds the number of notes in the melody, bad things will happen. For example, there is no value for melody[number_of_notes+1]. In fact, because of zero indexing, the highest defined note is only melody[number_of_notes-1].

So how do we deal with this? One answer is to simply use two variables. The first will be our random loop variable that will be the total number of notes to play. The second will be used to actually play the melody note. It will be incremented manually inside the loop, and once it exceeds the size of the melody, it will be set back to zero. That way the melody will loop.

Here's a second version of the sketch that makes these changes.

This guide was first published on Apr 05, 2017. It was last updated on Mar 08, 2024.

This page (Stopping a Melody) was last updated on Mar 08, 2024.

Text editor powered by tinymce.