Music from SD to TMRpcm"


The famous and well-known TMRpcm library written by TMRh20 enables you to play sampled music in the best quality the Arduino can provide.

Actually, all the examples I've seen so far - and I found many - require you know the file names stored on the SD card before and enter them in your sketch.
But this is not necessary. With the dir.openNextFile() command you can easily advance to the next file.

Using this code:

#include <TMRpcm.h>         
#include <SD.h>               
const byte SD_ChipSelectPin = 10;
File dir;
TMRpcm tmrpcm;   // create an object for use in this sketch

void setup() {
  tmrpcm.speakerPin = 9; 
  Serial.begin(9600);
  Serial.println(F(__FILE__));
  if (!SD.begin(SD_ChipSelectPin)) {
    // see if the card is present and can be initialized:
    Serial.println("SD fail");
    while (true);   // don't do anything more if not
  }
  Serial.println("SD ok");
  dir = SD.open("/");
}

void loop() {
  File entry =  dir.openNextFile();
  if (! entry) {
      // no more files
      // return to the first file in the directory
      dir.rewindDirectory();
      entry =  dir.openNextFile();
    }
  if (entry.isDirectory()) {
    entry.close();
    return;
  }
  Serial.print(entry.name());
  Serial.print("   ");
  Serial.println(entry.size());
  entry.close();
  tmrpcm.play(entry.name());
  while (tmrpcm.isPlaying());
}

you can create your own music player with any UNO, NANO, MINI and any SD adapter. Possibly, you have to modify the chip select pin to match your SD adapter.

The TMRpcm cannot handle WAV files in CD quality. If your original file format is 44100 (samples per second) STEREO 16-bit it has to be converted to 22050 MONO 8-bit.

How to convert the files?
This can be done with Audacity as documented in Format der WAVE Dateien or you can write your own script in any language you are familiar with; just modify the wave header and then
read LEFTn, RIGHTn,LEFTn+1,RIGHTn+1 and add them all.
Divide the result by 4 and again by 256. Add 128 to get the unsigned 8-bit WAV format.

Don't expect a super quality, especially if the source has a very dynamic.
Having uploaded this sketch, you can just replace the SD card by another one and listen to a different set of songs.

And, as the the files are played endlessly, don't blame me if you eventually suffer from an earworm.




contact: nji(at)gmx.de