This simple piano app uses 1 Canvas image to represent 29 piano keys, 1 ImageSprite mask to indicate where a key was pressed and 1 Player component to play the MIDI note of the pressed key.
When the user touches an area of the keyboard, the Canvas TouchDown event is used to 'snap-to-grid' that x,y position with a matching position from a list of button locations associated with the different MIDI notes.
The note is played and a blue mask displays over the 'touched' key.
When the finger is lifted, the note playback is Paused in the Canvas TouchUp event block and the mask is removed.
In this way, the action of press, play, sustain, suspend note playback can be simulated with a minimum of components.
Open the attached lrn_Canvas_TouchDown_advanced5.zip project.
Screen Designer:
The following were created and uploaded to the Media list:
- A keyboard image 100x816 pixels consisting of 29 keys was created with the GIMP image editor (keyboard816.png)
- A blue mask of 50% transparancy sized 50x48 is used to show the currently pressed key (mask.png)
- 29 MIDI files each consisting of a single whole note at 120 bpm in the range c4 to e6. (cn4.mid..en6.mid)
Blocks Editor:
Global variables-
key_MIDIs contains the list of note names associated with each of the 29 key positions on the keyboard_cnv background image.
key_Ys contains the list of Y-offsets from 0 of each key position on the keyboard_cnv.Background image.
key_X will hold either 0 for the ivory key bank X-offset or 50 for the ebony key bank X-offset.
index will hold either 0 (no match for touched area) or the index of the key at the touched location.
keyboard_cnv.TouchDown event block does the following:
- checks if the Touched x value is in the ivories (0..49) or ebonies (50..99) area, and uses the correct formula to determine a Y-value multiple of 48 offset to that position
- determines if that Y-offset is in the key_Ys list and if so returns it's index or a 0 if it is not found
- if the index is not 0, then it is used to select and play the correct MIDI file from the key_MIDIs list, and move and display the blue key mask ImageSprite at the key_X and y-value from the key_Ys list
keyboard_cnv.TouchUp event block-
- If the user touched a valid key on the keyboard, the index variable will not be 0, and if so the rest of the blocks will execute.
- If a note is playing, pause it.
- Hide the blue mask ImageSprite and reset the index to 0
Test the project.
Challenge: Include a way for the user to adjust the playback volume.