Play File

The speaker is also able to play monotone music encoded in a special format called wav files!

For this section to work, you must have installed on your Circuit Playground Express CircuitPython 2.3.1 or higher, or CircuitPython 3.0 Beta 1 or higher.

Sound files for the CPX library should be 22,050 kHz, 16-bit, mono (or less) WAV files to play on the Express boards. If you have an MP3 or a file you downloaded and are unsure of the encoding, you can follow this audio conversion guide to get your files into the proper format.

For testing, we've prepared two WAV files in the proper format. You can download the following two .wav files and copy them to your Circuit Playground Express CIRCUITPY drive.

Add the following code to your code.py. Remember, if you need help with this, check here.

from adafruit_circuitplayground.express import cpx

cpx.play_file("Wild_Eep.wav")

Eep!

Let's look at the code. First we import cpx.

Then, we play a wav file called "Wild_Eep.wav" with cpx.play_file("Wild_Eep.wav"). That's it!

Note that we did not include a loop in this code. This is because if the code is in a loop, it will continue playing indefinitely. This is not always desirable, so we've designed the code to play the file once.

cpx.play_file() requires one thing from you: the name of the wav file you're trying to play back in quotation marks. This is how it knows what file to play. So anytime you want to use it, you'll want to add cpx.play_file("Filename.wav") to your code, replacing Filename.wav with the name of your wav file.

Let's add some inputs and another wav file. Add the following code to your code.py.

from adafruit_circuitplayground.express import cpx

while True:
    if cpx.button_a:
        cpx.play_file("Wild_Eep.wav")
    if cpx.button_b:
        cpx.play_file("Coin.wav")

Now press button A. Eep! Press button B. Ding!

Inside the loop, we check to see if each button is pressed. If button A is pressed, we play "Wild_Eep.wav". If button B is pressed, we play "Coin.wav".

Notice if you press button B and then immediately try to press button A, the Coin.wav file completes before you're able to Eep again. This is because you cannot begin playing another file until the first file is completed. So, if you have a really long wav file, you'll find you can't do anything else until the file is finished playing. Keep that in mind if you're going to include wav files with other code.

You can use any of the inputs we've discussed to trigger a file to play. Try replacing the button presses with touch inputs. Try adding different files to use!

If your code is running but your file doesn't sound quite right or doesn't play back, be sure to check the encoding of your sound file by following this Adafruit guide.

Play More File Projects

Here are some projects that use play file:

This guide was first published on Jun 05, 2018. It was last updated on Jun 05, 2018. This page (Play File) was last updated on Dec 05, 2019.