arrow_back Walk to the Beat
In this add-on, you will write code that plays music when the user presses an arrow key.
To start, select the walking sprite, and add music or a sound clip.
You can upload music or choose a sound clip from the Scratch library.
This example uses the “dance slow mo” clip from the Scratch library.
Program the sound to play on repeat when the flag is clicked using the forever, “play sound until done,” and “when flag clicked” blocks.
Next, set the volume to 100% when the right arrow key or left arrow key is pressed.
Add another "when flag clicked" event and another "forever" loop.
Inside the forever loop, add an "if else" block.
Your program will say, "if left or right arrow key is pressed, then set volume to 100%."
Add an "or" block, and inside this, put a "key right arrow pressed" block on one side and a "key left arrow pressed" block on the other side.
In the "then" portion of the block, add a "set volume to" block and set the volume to 100%.
Next, set the volume to 0% when the right arrow key or the left arrow key is not pressed.
Add a "set volume" block to the "else" portion of the "if else" block, and change the value to 0%.
Click the flag, then the right arrow key to test.
The music plays!
Stop pressing the arrow key.
The music stops!
Well, it doesn't really stop, but you can't hear it anymore.
Press the left arrow key.
The music starts again.
The music plays when the left or right arrow keys are pressed, then becomes inaudible when they are not pressed.
There is no easy way to make music pause in Scratch, but this solution makes it so that the music does not start over from the beginning every time the user presses the right or left arrow keys.
Now, it's your turn.
Upload a sound or choose a sound from the Scratch library.
Program the sound to play on repeat when the flag is clicked.
Set the volume to 100% when the right or left arrow keys are pressed.
Set the volume to 0% when the right or the left arrow keys are not pressed.