Music
The mPython Board has an onboard passive buzzer whose sound is mainly produced by controlling pulse signals of different frequencies. The sound frequency is controllable - different frequencies produce different tones, allowing various sounds to be generated, including musical scales like “Do Re Mi Fa Sol La Si”.
Built-in Melodies
The mPython Board has many built-in melodies. The complete 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 Song
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 other melodies, simply replace music.BIRTHDAY with the desired melody name.
In addition to playing built-in melodies, we can also compose our own tunes.
Custom Tunes
We can compose tunes by setting 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. Duration is also represented as a number. The higher the duration value, the longer the note lasts. For example, duration 4 lasts twice as long as duration 2 (and so on). Each note is represented as a string in the following format:
NOTE[octave][:duration]
For example, C4:4 refers to the note “C” in octave 4, lasting 4 beats. If the note name R is used, it is treated as a rest (silence).
Frequency
You can also create non-musical tones by setting frequencies. 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)
In this example, the music.pitch method is used, which requires 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: start value, end value, and step. Therefore, the first use of range is “create a number range from 880 to 1760 with a step of 16”;
the second is “create a series of values from 1760 to 880 with a step of -16”, with a duration of 20 milliseconds per frequency. This creates a siren effect by ascending and descending through a frequency range.