Skip to content

Instantly share code, notes, and snippets.

@Fordi
Last active January 19, 2018 13:54
Show Gist options
  • Save Fordi/baa4330461f1ee202bf486ec1b46ffb9 to your computer and use it in GitHub Desktop.
Save Fordi/baa4330461f1ee202bf486ec1b46ffb9 to your computer and use it in GitHub Desktop.
Sample code to play a random MP3 file to the on-board DAC off the root of the on-board SD card on Teensy 3.5/3.6; For use with https://github.com/FrankBoesing/Arduino-Teensy-Codec-lib
#include <Audio.h>
#include <SerialFlash.h>
#include <play_sd_mp3.h>
#define USE_TEENSY3_OPTIMIZED_CODE
// SD-hosted MP3 file source
AudioPlaySdMp3 playMp31;
// Stereo DAC (Teensy 3.5/3.6)
AudioOutputAnalogStereo dacs1;
// Hook up the channels...
// source, srcChannel, target, tgtChannel
AudioConnection patchCord1(playMp31, 0, dacs1, 0);
AudioConnection patchCord2(playMp31, 1, dacs1, 1);
File root;
void setup() {
AudioMemory(40);
//Wait for SD to come available...
while (!(SD.begin(BUILTIN_SDCARD))) {
delay(500);
}
// Get a handle to the root folder so we can pick a file.
root = SD.open("/");
randomSeed(analogRead(0));
}
void playFile(const char *filename) {
int result = playMp31.play(filename);
if (result == ERR_MP3_NONE) {
// A brief delay for the library start decoding
delay(5);
// Simply wait for the file to finish playing.
while (playMp31.isPlaying()) {
//Don't work so hard.
delay(25);
}
} else if (result == 1) {
Serial.println("SD Card unplugged; halting.");
while (true) { delay(5000); }
} else {
Serial.print("Result: ");
Serial.print(result);
Serial.println("Halting.");
while (true) { delay(5000); }
}
}
void playRandomFile() {
File files[256] = {};
int len = 0;
while (len < 256) {
File entry = root.openNextFile();
if (!entry) { break; }
if (isMp3(entry.name())) {
files[len++] = entry;
}
}
len -= 1;
root.rewindDirectory();
int idx = random(0, len);
playFile(files[idx].name());
}
// Simple filename test
bool isMp3(char* filename) {
int len = strlen(filename);
return strstr(filename + (len - 4), ".MP3");
}
void loop() {
while (true) {
playRandomFile();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment