Salvatore Sanfilippo Gets the Raspberry Pi Pico Playing Audio Back, No External DAC Necessary
At the cost of tying up one of the RP2040's two Arm Cortex-M0+ cores, you too can get PCM audio playback with no additional hardware.
Programmer Salvatore Sanfilippo has come up with a way to play recognizable audio from a Raspberry Pi Pico, without the need for an external digital to analog converter (DAC) — using only a single pin and the RP2040's pulse-width modulation (PWM) capabilities.
"One of the cool things one wants to do with an MCU [Microcontroller Unit] like [the RP2040] is generating some sound," Sanfilippo writes. "The most obvious way to do this is using the built-in PWM feature of the chip. The GPIOs [General-Purpose Input/Output pins] can be configured to just alternate between zero and one at the desired frequency — [but] there are little sounds as terrible to hear as square waves."
To turn a simple on-and-off signal into something you can not just tolerate but recognize, Sanfilippo wrote a MicroPython program that takes as its input an eight-bit raw PCM audio recording converted from a WAV file using ffmpeg, maps it to 16 bits, and uses it to set the duty cycle on a pulse-width modulated signal coming from one of the Raspberry Pi's GPIO pins.
"The downside of all this is that it will take your program busy while playing," Sanfilippo says of the program's downside. "I didn't test it yet, but MicroPython supports threading, so to have a thread playing the audio could be the way to go" — and with the Raspberry Pi RP2040 having two Arm Cortex-M0+ cores, it should be possible to have one core dedicated to audio playback and still use the other core for the rest of your program.
Sanfilippo's write-up is available, with sample code, on his website.