Music
The mPython Board has an onboard speaker. The main controller IO generates pulse signals of different frequencies, which are power-amplified and emitted as sound through the speaker. Different frequencies produce different pitches, so various sounds can be produced, achieving a “do-re-mi-fa-sol-la-si” effect.
Built-in Melodies
The mPython Board has many built-in melodies; the full list is as follows:
music.DADADADUMmusic.ENTERTAINERmusic.PRELUDEmusic.ODEmusic.NYANmusic.RINGTONEmusic.FUNKmusic.BLUESmusic.BIRTHDAYmusic.WEDDINGmusic.FUNERALmusic.PUNCHLINEmusic.PYTHONmusic.BADDYmusic.CHASEmusic.BA_DINGmusic.WAWAWAWAAmusic.JUMP_UPmusic.JUMP_DOWNmusic.POWER_UPmusic.POWER_DOWNGE_CHANG_ZU_GUO- Ode to the MotherlandDONG_FANG_HONG- The East Is RedCAI_YUN_ZHUI_YUE- Colored Clouds Chasing the MoonZOU_JIN_XIN_SHI_DAI- Into the New EraMO_LI_HUA- Jasmine FlowerYI_MENG_SHAN_XIAO_DIAO- Yimeng Mountain Folk Tune
We can play some built-in melodies:
import music
music.play(music.BIRTHDAY)
Tip
music.BIRTHDAY refers to the name of a built-in melody. To play another melody, simply replace music.BIRTHDAY with the melody you want to play.
Besides playing built-in melodies, we can also compose our own scores.
Composing Your Own Score
We can compose our own score by setting the notes.
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 is the lowest octave, 4 is middle C, and 8 is as high as you need. The duration is also expressed as a number. The higher the duration value, the longer the note lasts. For example, a duration of 4 lasts twice as long as a duration of 2 (and so on). Each note is represented by a string of characters, as shown below:
NOTE[octave][:duration]
For example, C4:4 refers to the note “C” in octave 4, lasting 4 ticks. If the note name R is used, it is treated as a rest (silence).
Frequency
You can also create non-note tones by setting the frequency. For example, to create 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)
This example shows how to use the music.pitch method, which takes a frequency.
The range function is used to generate a range of numbers. These numbers define the pitch of the tone.
The range function has three parameters: the start value, the end value and the step. Therefore, the first use of range means “create a range of numbers from 880 to 1760 with a step of 16”;
the second means “create a series of values from 1760 to 880 with a step of -16”, each frequency lasting 20 milliseconds. This yields a frequency range that rises and falls like a siren, creating the siren effect.