4. Music¶
The passive buzzer built on the mPython board, its sound is mainly generated by the different levels of pulse signals. The frequency of the sound is controllable, different frequency to emit different tone, thus produce different sound effect of “duō lái mǐ fā suǒ lā xī”.
4.1. Melody pre-installed¶
The list of melodies included in mPython Board is as follows:
music.DADADADUM
music.ENTERTAINER
music.PRELUDE
music.ODE
music.NYAN
music.RINGTONE
music.FUNK
music.BLUES
music.BIRTHDAY
music.WEDDING
music.FUNERAL
music.PUNCHLINE
music.PYTHON
music.BADDY
music.CHASE
music.BA_DING
music.WAWAWAWAA
music.JUMP_UP
music.JUMP_DOWN
music.POWER_UP
music.POWER_DOWN
GE_CHANG_ZU_GUO
DONG_FANG_HONG
CAI_YUN_ZHUI_YUE
ZOU_JIN_XIN_SHI_DAI
MO_LI_HUA
YI_MENG_SHAN_XIAO_DIAO
To play these melodies:
import music
music.play(music.BIRTHDAY)
prompt
music.BIRTHDAY refers to the name of the built-in melody, if you want to play other melody, just replace music.BIRTHDAY with the melody you want to play.
In addition to the melodies list, you can also compose your own music.
4.2. Compose your own music¶
Set the tone to cumpose your own music.
import music
tune = ["C4:4", "D4:4", "E4:4", "C4:4", "C4:4", "D4:4", "E4:4", "C4:4",
"E4:4", "F4:4", "G4:8", "E4:4", "F4:4", "G4:8"]
music.play(tune)
Each note has a name (such as C # or F), an octave and a duration. The octave is represented by a number ~ 0 means the lowest octave, 4 means the central C, and 8 means the height you need. The duration is also expressed as a number. The higher the duration value, the longer the duration. For example, duration 4 will last twice as long as duration 2 (and so on). Each note is represented as a string of characters, as shown below:
NOTE[octave][:duration]
For example, C4:4 refers to the note “C”,in octave 4 and lasts 4 scales. If the note name R is used, it is regarded as resting (silent).
4.3. Frequency¶
You can also make some non-note tones through the frequency setting. For example, creating a siren effect:
import music
while True:
for freq in range(880, 1760, 16):
music.pitch(freq, 50)
for freq in range(1760, 880, -16):
music.pitch(freq,50)
How to use the music.pitch
method in this example, it needs a frequency.
The range function is used to generate a numerical range. These numbers are used to define the pitch.
The range function has three parameters, which are the start value, end value, and step size. Therefore, the first use of range was “to create a number range between 880 and 1760 in steps of 16”;
The second time is to create a series of values between 1760 and 880 in “-16” steps with a sustained frequency of 20 ms. Therefore, a siren effect is due to the ascending and descending frequency.