Chapter 11. Sound and Music

Sound is an intriguing medium. We use it to signal (such as the ringing of a mobile phone), create art (with music) and communicate meaning (through speech). If a device can make sound, it can signal, make music, and maybe even speak to us. There’s also something deeply satisfying in making things go “bloop”.

Three of the devices are immediately able to create sound. The Circuit Playground Express has a built-in speaker, the PyBoard has an AMP audio skin and the micro:bit comes with modules for making sounds if you attach speakers to it via the GPIO pins.

This chapter explores all the ways in which you can make sounds, music, and speech with MicroPython.

Bleeps and Bloops

The speaker on the Circuit Playground Express, like all things that produce sound, needs to create vibrations in the air. The simplest way to do this is to switch the buzzer on and off very quickly, thus making it vibrate to create a sound whose pitch is determined by how quickly the vibrations are oscillating. The following code demonstrates how to make the buzzer go “bloop” for two seconds:

 import audioio import array import time import digitalio from board import SPEAKER, SPEAKER_ENABLE # Switch on the speaker for output. speaker_enable = digitalio.DigitalInOut(SPEAKER_ENABLE) speaker_enable.switch_to_output(value=True) duration = 2 length = 8000 // 1760 wave = array.array("H", [0] * length) wave[0] = int(2 ** 15 - 1) with audioio.AudioOut(SPEAKER, wave) as speaker: speaker.play(loop=True) ...

Get Programming with MicroPython now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.