Sparkfun MP3 Shield Arduino Library

Posted in Arduino Libraries by Bill
28 Jan 2012

The Sparkfun MP3 Player Shield for Arduino is a inexpensive and easy way to add MP3 playback capability to your Arduino project. But it was lacking an easy to use Arduino Library to go along, so I fixed that. Introducing the SFEMP3Shield library just for this shield. Now playing an MP3 files is as easy as MP3player.playTrack(5); and all the work is done behind the scenes.

Most of this library comes from the existing example code, with the major new feature of being interrupt driven. So no need to worry about feeding the MP3 chip, whenever it’s ready for more the library will be ready to feed it. This allows the Arduino to perform other tasks while music is playing. The most basic use of the library is as follows:

 

#include <SPI.h>
#include <SdFat.h>
#include <SdFatUtil.h> 
#include <SFEMP3Shield.h>

SdFat sd;
SFEMP3Shield MP3player;

void setup() {

  Serial.begin(9600);

  //start the shield
  sd.begin(SD_SEL, SPI_HALF_SPEED);
  MP3player.begin();

  //start playing track 1
  MP3player.playTrack(1);
}

//do something else now
void loop() {

  Serial.println("I'm bored!");
  delay(2000);

}

That’s all it takes to get your Arduino to play an MP3 file using the shield.  How easy is that?

The library does have more functions and even error reporting. All of which can be found in the ReadMe file or in the Example Sketch included with the Library.

Source Code available on GitHub project pages: Sparkfun MP3 Player Shield Arduino Library

Or Direct Download here.

Using the SPI bus for something else as well?

I added some functions to make sure there will be no data collisions on the SPI bus caused by the MP3 decoder asking for more data at the wrong time. You need to wrap any SPI code you add to your project with these two functions. Here’s an example from my project that also has a shift register on the SPI bus:

  //disable interrupts to avoid collisions on the SPI bus between this code //and the MP3player library
  MP3player.pauseDataStream();

  //shift data
  tempIO = SPI.transfer(HIBYTE(output));
  tempIO<<8; 
  tempIO = SPI.transfer(LOBYTE(output));

  //latch output on shift registers
  digitalWrite(OUTLATCH,LOW);
  digitalWrite(OUTLATCH,HIGH);
  digitalWrite(OUTLATCH,LOW);

  //enable interrupts
  MP3player.resumeDataStream();

But you can’t stop the data stream to the MP3 Shield for too long before it runs out of data so be careful and try not to do too much stuff in between the functions.

 

Wanna be your own DJ?

New features! Requested in the comments below, there are now functions to skip around a playing track. You could fast forward, rewind, create loops, etc.

Here’s an example that will just open a file, jump to the 30 second mark (measured in milliseconds, 30 seconds = 30000 ms), and loop the song back every 750 ms:

MP3player.playTrack(1);

for(;;) {
MP3player.skipTo(30000);
delay(750);
}

If you want to know where you are in the current playback, do this:

time = MP3player.currentPosition();
Serial.println(time);

Both functions are not super accurate and depend on the bitrate of the file. The library should auto-detect the bitrate of the file but may fail on some MP3 files. If that happens, you have to set the bitrate manually like this:

MP3player.playTrack(1);
MP3player.setBitRate(192);

I can already see the cool DIY DJ equipment that could be made with this. Let me know if you have problems, and comment below if you ever make something cool with the library.

Troubleshooting

Pulled from the GitHub Project Page

The below is a list of basic questions to ask when attempting to determine the problem.

  • Did it initially PRINT the available RAM and Full Help Menu?
    • The MP3Shield_Library_Demo.ino example should initially provide a opening print indicating the amount of available SRAM and full menu help. If you don’t see this the problem is between your Target and IDE. And likely not this library
    • Is Serial Monitor set to the correct tty or com port and 115200 baud rate? Did you change the baud rate?
    • Reset the Arduino after Serial Monitor is open or send any key. It may have printed these prior to the Serial Monitor being started.
  • WHAT is the Error reported?
    • Is the Error Code is indicating a file problem.
    • Are the filenames 8.3 format? See below warning.
    • See also Error Codes
  • Did the SdCard LOAD?
    • Try reseating your SdCard.
  • Is it FAT(FAT16 or FAT32)?
    • If the Error Code is indicating problems with the INIT, VOLUME or Track not being successful. It is recommend to use SdFat Example Library’s QuickStart.ino as to see if it can access the card. Additionaly, SdInfo.ino may indicate if it can mount the card. Which may then need to formatted in FAT16 or FAT32. Where SdFormatter.ino can do this for you.
  • Are the needed files on the root?
    • Remember to put patch and audio track files on the SdCard after formatting.
    • Are the filenames 8.3 format? See below warning.
  • "Error code: 1 when \b trying to play track"
    • See the above Limitations. about Non-Blocking.
    • Remember to check your audio cables and volume.
  • Why do I only hear1 second of music, or less?
    • This symptom is typical of the interrupt not triggering the SFEMP3Shield::refill(). I bet repeatidly sendnig a track number will advance the play about one second at a time, then stop.
    • What board is it? Check Hardware Limitations. about Interrupts.
    • Are you trying the SFE provided test files ? Or some homemade mp3 files? The SFE test files are nice as they are Immediately LOUD.
    • Interrupt problems may cause mp3 files that have a quiet lead in (or ramp up of volume) to be falsely diagnosed as not playing at all. Where the first 1 second may not be loud enough to be heard.
  • Free RAM = 1090 Should be a base line of 1094
    • As a courtesy and good practice the provided example MP3Shield_Library_Demo.ino prints out the available remaining RAM, not statically allocated. And the actual available amount may depend on specific processor, IDE version, libraries and or other factors. A Uno built with IDE version 1.0.2 should have approximately 1094 bytes available from the example as is. And a Mega using a 2560 may show 6713, as it has more RAM.

Note

This library makes extensive use of SdFat Library as to retrieve the stream of audio data from the SdCard. Notably this is where most failures occur. Where some SdCard types and manufacturers are not supported by SdFat. Though SdFat Lib is at this time, supporting most known cards.

 

Warning

SdFatLib only supports 8.3 filenames. Long file names will not work. Use the 'd' menu command to display directory contents of the SdCard. "longfilename.mp3" will be converted to "longfi~1.mp3" . Where one can not predict the value of the 1. The DOS command of "dir \c /x" will list a cross reference, so that you know exactly, what is what.

Still Need Help?

Use the support forum to look for a solution or ask for help. Please don’t use the comments below to ask for help.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.

Share

Trackbacks / Pingbacks

  1. The Cat's Meow: MP3 Shield Tutorial | Adventures in Art
  2. The Mind of Bill Porter

Warning: count(): Parameter must be an array or an object that implements Countable in /homepages/46/d285670699/htdocs/bill/wp-includes/comment.php on line 879
  1. 590 Comments.

    • Michael P. FlagaNo Gravatar says:

      There is definitely a conflict. Please read the schematic and or the libraries as they indicate which pins are being used, by the Shield. I often use A0-A5 as quick and available by this shield.

    • Spam engineNo Gravatar says:

      Does your blog have a contact page? I’m having problems locating it but, I’d like to shoot you
      an e-mail. I’ve got some creative ideas for your blog you might be interested in hearing. Either way, great website and I look forward to seeing it grow over time.

    • […] SD card needs to be formatted for Fat 16 or Fat 32. Bill Porter’s library for the SD card includes a SDInfo.ino for greater […]

    • IgorNo Gravatar says:

      As a total beginner in uC world, I must rely on existing code examples and libraries, but after reading comments and hints found here I’ve managed to get my UNO R3+MP3shield up and running!!!

      Awesome library, great support and I can’t thank you enough, keep up the good work!

    • Alberto SilvaNo Gravatar says:

      sorry for my bad english.
      the problem I have is that when I compile the code, it gives me the error 4
      “Other than default values ​​were found in the SCI_MODE register.”
      I’ve tried 3 cards, 2= 2GB and 1= 4GB, I used the library SDfat to format them.
      the response in the serial monitor when i digit (i, m) is the following:
      “Received command: i
      HDAT1 HDAT0 VOL Mode Status ClockF pversion [Bytes/S] [KBits/S] PlaySpeed DECODE_TIME CurrentPos
      0x0 0x0 0x0 0x0 0x0 0x0 0x0 0 0 0 0 0
      Enter 1-9,f,F,s,d,+,-,i,>,,<,p,r,R,t,m,M,g,k,h,O,o,D,S,V :
      Received command: 1
      Playing:
      any idea please

      • Michael P. FlagaNo Gravatar says:

        Please review the forums and github page documentation. Where “Other than default values ​​were found in the SCI_MODE register.” is about the VS1053 chip and not the SdCard. During initial setup it writes and reads back the VS1053 register to validate that it is properly communicating to it. Yours is not. Hence nothing subsequent will properly work.

    • Alberto SilvaNo Gravatar says:

      sorry, missing some information:
      “Received command: i
      HDAT1 HDAT0 VOL Mode Status ClockF pversion [Bytes/S] [KBits/S] PlaySpeed DECODE_TIME CurrentPos
      0x0 0x0 0x0 0x0 0x0 0x0 0x0 0 0 0 0 0
      Enter 1-9,f,F,s,d,+,-,i,>,,<,p,r,R,t,m,M,g,k,h,O,o,D,S,V :
      "

    • I do not know what is happening, but the information of the memory test is not passed, the result is as follows:
      Memory Test Results = 0
      Result should be 0x83FF.

    • BradNo Gravatar says:

      I am new to arduino and am trying to use your (excellent) code for part of a school project I am working on. I am also trying to utilize my arduino for an lcd screen and an rtc clock module. Can anyone help me with what I/O pins are NOT being used by this mp3 shield code? I need to know so that I can use those pins for other functions. Thanks!

      • BillNo Gravatar says:

        Brad,

        Your safest bet is to use all the Analog pins. They can also be used as digital pins. Do you need more than 6 pins for your project? There is not many left after the MP3 shield for pins 0-13.

    • […] library for Arduino. Both Arduino’s use this library for the DMX control. Of course I used my own library to run the MP3 Shield, and pulled in this easy library to run the MP3 Trigger […]

    • victorNo Gravatar says:

      hi,
      First of all, thanks for this job! It is great!
      When I use the delay function, it take aprox. 1.4 times the time I set, for example, if I use delay(10000) it takes about 14 seconds, not 10.
      Is it possible to fix it? is this unwanted delay constant?

      Thanks

      • Michael P. FlagaNo Gravatar says:

        Does the delay appear differently when playing versus not playing? Have you tried slower bit rate files? Higher bitrate’s may take too much real time in reading the SdCard and writing the VSdsp, blocking TIMER0’s count of each millis.

        This question can be better followed on the forum. Thanks.

        • victorNo Gravatar says:

          Hi,

          -Using the first code, I disableed the seriall communication(by commenting the necessary:
          //serial.begin(9600); and
          //Serial.println(“I’m bored!”);
          In this case the seriall comumuniction(for the seriall monitor) doesn’t take any time.

          -The new code wants to play only 10 seconds of the first 3 tracks, but the music if I set a delay(10000), it takes about 14 seconds playing each song…

          – I don’t tried if this unwanted delay appears also when no music is playing…

          Thanks!!!

    • KaiNo Gravatar says:

      Bill, thank you very much for this code! Very,very nice!

    • Brian MagnusonNo Gravatar says:

      How many tracks will it play. Can you set it up with lots of buttons like a sound board?

      • Michael P. FlagaNo Gravatar says:

        you can custom write your own sketch to play as many files as you want, several examples were included. The man demo is limited to 10 files. but FilePlayer.ino up to 99,999. Also look at this example MP3ButtonPlayer.ino found at https://gist.github.com/mpflaga along with a few others that I have created from some questions.

    • VandroNo Gravatar says:

      Hello, I tested with Arduino Uno and Ethernet shield W5100, want a web player, and it worked. But is not working with the mega 2560 (​​XDRduino), I tried calling the doors 9,11,12,13 pins 53, 51, ​​50, 52. Could you help me?

    • rcornejo82No Gravatar says:

      I have a PIR sensor wired to PIN12 and once it detects movement the Mp3Shield plays a sound. Everything works for some amount a time, and then the PlayTrack functions stops working. PlayTrack does not return a value and it gets cycled. Does this have happens because I am using PIN 12?? MISO

    • Martin BoroffNo Gravatar says:

      will this shield work with an ethernet shield. I currently can not read the sd card on a wave shield with it stacked on top of an Ethernet shield.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.