Example Code for Arduino-Play WAV File
Last revision 2025/12/27
This article guides users through the process of setting up Arduino to play WAV files, including necessary hardware, software, and sample code.
Hardware Preparation
- DFRduino M0 Mainboard(SKU: DFR0392) ×1
- Audio Shield for DFRduino M0(SKU:DFR0420) ×1
- 3.5mm headphone or 3W Speaker
- MicroSD card with FAT format (Currently, exFAT is not supported. Please use FAT16 or FAT32 for formatting)
Software Preparation
- Download Arduino IDE (Version requirements: V1.6+): Click to Download Arduino IDE
Other Preparation Work
- Leave your wav file on the root of Micro-SD card. (Named with "test.wav") ,
- Insert your SD card into the SD card slot. Note: SD storage format must be FAT
- Plug in speakers or headphones
- Upload the sample code, open the serial port monitor, and it will play themusic.
Sample Code
Play WAV music.
#include <SPI.h>
#include <Wire.h>
#include <SD.h>
#include <WAV.h>
// set up variables using the SD utility library functions:
Sd2Card card;
///< assign sd card chipselect pin
const int chipSelect = 30;
void setup()
{
// Open serial communications and wait for port to open:
Serial.begin(115200);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
while(1){
Serial.print("\nInitializing SD card...");
// we'll use the initialization code from the utility libraries
// since we're just testing if the card is working!
if (!card.init(SPI_HALF_SPEED, chipSelect)) {
Serial.println("initialization failed. Things to check:");
Serial.println("* is a card inserted?");
Serial.println("* is your wiring correct?");
Serial.println("* did you change the chipSelect pin to match your shield or module?");
delay(2000);
continue;
} else {
Serial.println("Wiring is correct and a card is present.");
if (!SD.begin(chipSelect)) {
Serial.println("Card failed, or not present");
delay(2000);
continue;
}
break;
}
}
}
void loop()
{
int ret;
//assign music file and trigger transport dma
wav.play("test.wav");
do{
//We must continue to decode to provide data to the player
ret = wav.decode();
//user code
}while(ret == WAV_DECODING);
while(1);
}
Result
It will play the music.
Was this article helpful?
