|
A melody is played be creating a melody list or tuple were the pitch and the duration of each tone is are defined by consecutive strings. The pitch in musical notation and the duration in number of ticks. If no ticks is given, the value 1 is assumed. A typical examples is the following melody tuple that is predefined as variable music.ENTERTAINER:
('d4:1', 'd#', 'e', 'c5:2', 'e4:1', 'c5:2', 'e4:1', 'c5:3', 'c:1', 'd', 'd#', 'e', 'c', 'd', 'e:2', 'b4:1', 'd5:2', 'c:4')
(The case of musical notes does not matter.)
Aim:
Play the ENTERTAINER melody each time you press the button A. When button B is pressed the program finishes.
Program:
# Entertainer.py
from microbit import *
from music import *
print(ENTERTAINER)
while not button_b.is_pressed():
play(ENTERTAINER)
while not button_a.is_pressed() and not button_b.is_pressed():
sleep(10)
|
Remarks:
button_a.is_pressed() and button_b.is_pressed() returns True as long as one of the button is pressed and hold down. Try to understand why button_b.was_pressed() could not replace button_b.is_pressed() in this example. The speed of the melody can be adapted by the set_tempo() function. For more information consult the microbit API (link in the right side bar).
|