O'Reilly logo

Programming with MicroPython by Nicholas H. Tollervey

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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) ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required