Simple Audio Player

Description

This example shows how to use the Audio library of the Arduino STAR OTTO, to play a sound file, named test.wav in the root directory of a Micro SD card.

Note:
Only 22kHz and 48kHz supported for now.

Hardware

Circuit

Mount the SD card in the dedicated slot, plug in a speaker at the Audio connector and finally connect the board to PC.
Star Otto

Code

Now upload the code below, using the Arduino IDE.

Warning:
Use the Arduino IDE 1.8.x and download the corresponding platform (Arduino STM32F4 Boards) from the Board Manager
The Audio library is already included in the IDE, select the Arduino STAR OTTO as board to see the Audio Examples in the menu:

Simple Audio sketch


/*
Simple Audio Player

Demonstrates the use of the Audio library for the Arduino OTTO

Hardware required :
* SD card in the Arduino OTTO slot
* A sound file named "test.wav" in the root directory of the SD card
* Only 22kHz and 48kHz supported for now
* A speaker to connect to the audio amplifier

Original by Massimo Banzi September 20, 2012
Modified by Scott Fitzgerald October 19, 2012
Modified by Laurent Meunier 2016 - based with STM32 MCD Application examples support
Modified by Francesco Alessi October 25, 2016

This example code is in the public domain
*/

#include <SD.h>
#include <Audio.h>

void setup() {
// initialize serial communication at 9600 bits per second:
SerialUSB.begin(115200);
while(!SerialUSB);

/* Test begin() method */
while (SD.begin(SD_DETECT_PIN) != TRUE)
{
delay(10);
}
}

void loop() {
int count = 0;
WAVE_FormatTypeDef WaveFormat;
const int S = 1024; // Number of samples to read in block
uint32_t buffer[S];
int duration;
delay(1000); // delay for console

File myFile = SD.open("test.wav");
if (!myFile.available()) {
// if the file didn't open, print an error and stop
SerialUSB.println("error opening test.wav");
while (true);
} else {
SerialUSB.println("test.wav open OK");
}

myFile.read((void*) &WaveFormat, sizeof(WaveFormat));

delay(1000);
SerialUSB.println("STARTUP AUDIO\r\n");
delay(1000);
Audio.begin(WaveFormat.SampleRate, 100);

delay(1000);

// Prepare samples
int volume = 50;
Audio.prepare(NULL, S, volume);

delay(1000);

while (myFile.available()) {
// Every 100 block print a '.'
count++;
if (count == 1000) {
SerialUSB.print(".");
count = 0;
}
// read from the file into buffer
myFile.read(buffer, sizeof(buffer));

// Feed samples to audio
Audio.write(buffer, sizeof(buffer));
}
/* reaching end of file */
SerialUSB.println("End of file. Thank you for listening!");
Audio.end();
myFile.close();

delay(5000);
SerialUSB.println("Restart Playing");

}

Output

Now listen the sound from the speaker.