We started with a basic plan:
- 1 Piano Sprite
- 3 Button Sprites
- A list to store all the possible Piano notes.
- A list to store the tune being played.
Luckily Scratch comes with a Piano Sprite, which we used and expanded it to fill the width of the screen.
Next step was to create the list of all the notes, there are 14 keys on the Piano so we need at least 14 notes in our list.
We found out what notes are possible by using one of the Sound blocks and looking at what was possible
This gave us our list of possible notes:
Now on to the code…
We needed to work out what key on the Piano had been clicked, and convert it to a number between 1 and 14 so we could play the correct note from the list.
This required some tricky calculations, to convert the Mouses “X” position to a positive integer between 1 and 14.
- First we added a number to make X always positive
- Second we divided that by the size of a note.
- And finally we rounded it up, using the ceiling function.
This ended up with the following code and a couple of Variables to store the “Extra” number to make X positive and the size of a note:
Once we had the positive integer we could use it to select the correct note to play from the list:
We did start some of the Buttons, and we will complete them next week. Notes for the buttons will be included then.
In order to make the Piano a bit more usable we added 3 Buttons:
All three Buttons had two costumes, we used the second costume to change the colour of the Button, this made it easy to see if you had clicked the button or not.
The Record button, simply set a Data Flag to indicate to the Piano code that it should “record” the notes being played in a List variable.
It also flashed while recording was “on”, this is the code for the Record Button:
We also had to add some additional code to the Piano to make sure the notes were recorded:
The Stop button was quite simple, we just set the Data Flag back to 0, and changed the costume for a short while to make it clear that the button had been pressed.
The Play button was a little more complex as it need to read all the items in the List and play the correct notes. It also flashed while playing. This is the code from the Play button:
The Final project looked something like this, you can get a copy from the Scratch Web Site, see the Notes below.
Note: My version of the project has been uploaded to https://scratch.mit.edu you can Sign in using the following details:
- Username : cdadvancers1819
- Password : advancers
- Project Name is : Class-Piano