Though the following example uses the Circuit Playground Express to demonstrate, the code works exactly the same way with the Circuit Playground Bluefruit. Simply copy the code and follow along with your Circuit Playground Bluefruit!

The Circuit Playground Express has some nice built in audio output capabilities.

There are two ways to get audio output, one is via the small built in speaker. The other is by using alligator clips to connect a headphone or powered speaker to the A0/AUDIO pin.

The speaker is over here, its small but can make some loud sounds! You can ENABLE or disable the speaker. If you disable the speaker, audio will only come out the A0/AUDIO pin. If you enable the speaker, audio will come out from both!

If you want to connect a speaker or headphones, use two alligator clips and connect GND to the sleeve of the headphone, and A0/AUDIO to the tip.

The A0/AUDIO pin cannot drive a speaker directly, please only connect headphones, or powered speakers!

Basic Tones

We can start by making simple tones. We will play sine waves. We first generate a single period of a sine wave in python, with the math.sin function, and stick it into sine_wave.

Then we enable the speaker by setting the SPEAKER_ENABLE pin to be an output and True.

We can create the audio object with this line that sets the output pin and the sine wave sample object and give it the sample array

audio = AudioOut(board.SPEAKER)
sine_wave_sample = RawSample(sine_wave)

Finally you can run audio.play() - if you only want to play the sample once, call as is. If you want it to loop the sample, which we definitely do so its one long tone, pass in loop=True

You can then do whatever you like, the tone will play in the background until you call audio.stop()

In the example below, click the Download Project Bundle button below to download the necessary files in a zip file. Extract the contents of the zip file, open the directory Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_AudioSine/ and then click on the directory that matches the version of CircuitPython you're using and copy code.py to your CIRCUITPY drive.

Your CIRCUITPY drive should now look similar to the following image:

CIRCUITPY
# SPDX-FileCopyrightText: 2017 Limor Fried for Adafruit Industries
#
# SPDX-License-Identifier: MIT

import time
import array
import math
import board
import digitalio

try:
    from audiocore import RawSample
except ImportError:
    from audioio import RawSample

try:
    from audioio import AudioOut
except ImportError:
    try:
        from audiopwmio import PWMAudioOut as AudioOut
    except ImportError:
        pass  # not always supported by every board!

FREQUENCY = 440  # 440 Hz middle 'A'
SAMPLERATE = 8000  # 8000 samples/second, recommended!

# Generate one period of sine wav.
length = SAMPLERATE // FREQUENCY
sine_wave = array.array("H", [0] * length)
for i in range(length):
    sine_wave[i] = int(math.sin(math.pi * 2 * i / length) * (2 ** 15) + 2 ** 15)

# Enable the speaker
speaker_enable = digitalio.DigitalInOut(board.SPEAKER_ENABLE)
speaker_enable.direction = digitalio.Direction.OUTPUT
speaker_enable.value = True

audio = AudioOut(board.SPEAKER)
sine_wave_sample = RawSample(sine_wave)

# A single sine wave sample is hundredths of a second long. If you set loop=False, it will play
# a single instance of the sample (a quick burst of sound) and then silence for the rest of the
# duration of the time.sleep(). If loop=True, it will play the single instance of the sample
# continuously for the duration of the time.sleep().
audio.play(sine_wave_sample, loop=True)  # Play the single sine_wave sample continuously...
time.sleep(1)  # for the duration of the sleep (in seconds)
audio.stop()  # and then stop.

Playing Audio Files

Tones are lovely but lets play some music! You can drag-and-drop audio files onto the CIRCUITPY drive and then play them with a Python command

Installing Project Code

To use with CircuitPython, you need to first install a few libraries, into the lib folder on your CIRCUITPY drive. Then you need to update code.py with the example script.

Thankfully, we can do this in one go. In the example below, click the Download Project Bundle button below to download the necessary libraries and the code.py file in a zip file. Extract the contents of the zip file, open the directory Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_AudioFiles/ and then click on the directory that matches the version of CircuitPython you're using and copy the contents of that directory to your CIRCUITPY drive.

Your CIRCUITPY drive should now look similar to the following image:

CIRCUITPY
# SPDX-FileCopyrightText: 2017 Limor Fried for Adafruit Industries
#
# SPDX-License-Identifier: MIT

import board
import digitalio

try:
    from audiocore import WaveFile
except ImportError:
    from audioio import WaveFile

try:
    from audioio import AudioOut
except ImportError:
    try:
        from audiopwmio import PWMAudioOut as AudioOut
    except ImportError:
        pass  # not always supported by every board!

# Enable the speaker
spkrenable = digitalio.DigitalInOut(board.SPEAKER_ENABLE)
spkrenable.direction = digitalio.Direction.OUTPUT
spkrenable.value = True

# Make the 2 input buttons
buttonA = digitalio.DigitalInOut(board.BUTTON_A)
buttonA.direction = digitalio.Direction.INPUT
buttonA.pull = digitalio.Pull.DOWN

buttonB = digitalio.DigitalInOut(board.BUTTON_B)
buttonB.direction = digitalio.Direction.INPUT
buttonB.pull = digitalio.Pull.DOWN

# The two files assigned to buttons A & B
audiofiles = ["rimshot.wav", "laugh.wav"]


def play_file(filename):
    print("Playing file: " + filename)
    wave_file = open(filename, "rb")
    with WaveFile(wave_file) as wave:
        with AudioOut(board.SPEAKER) as audio:
            audio.play(wave)
            while audio.playing:
                pass
    print("Finished")


while True:
    if buttonA.value:
        play_file(audiofiles[0])
    if buttonB.value:
        play_file(audiofiles[1])

This example creates two input buttons using the onboard buttons, then has a helper function that will:

  1. open a file on the disk drive with wave_file = open(filename, "rb")
  2. create the wave file object with with WaveFile(wave_file) as wave:
  3. create the audio playback object with with AudioOut(board.SPEAKER) as audio:
  4. and finally play it until its done:
    audio.play(wave)
    while audio.playing:
        pass

 Upload the code then try pressing the two buttons one at a time to create your own laugh track!

If you want to use your own sound files, you can! Record, sample, remix, or simply download files from a sound file site, such as freesample.org. Then, to make sure you have the files converted to the proper specifications, check out this guide here that'll show you how! Spoiler alert: you'll need to make a small, 22Khz (or lower), 16 bit PCM, mono  .wav file!

This guide was first published on Sep 12, 2019. It was last updated on Jul 14, 2024.

This page (CircuitPython Audio Out) was last updated on Jul 13, 2024.

Text editor powered by tinymce.