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

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.

    • Finally got it! I thought the plugins had to be in with the library. Once the were on my SD everything worked. Thanks for all your help. I’m gonna donate a few bucks to the project. It’s the least I could do!

      • FlagaNo Gravatar says:

        Great to hear.
        You have peaked my interest with the Ethernet.

        Did you say you had some of the Ethernet and MP3 working while using the UNO? How far along did you get, if anything working.

        I have taken github.com/adafruit/SDWebBrowse and added mp3 play, not to hard. Where server.available(); appears to disable the interrupt, stopping the MP3 playing.

      • FlagaNo Gravatar says:

        …Karma and Carson Daly…

        The Ethernet card support INT0 on D2 like the SFEMP3Shield, which is not used with a jump open. So it should not interfere. However, I believe the Ethernet library supports this when connected. So I believe (not sure) that it is turning off the interrupts at some point.

        That said we previously exampled in this forum replacing the INT0 interrupt with a SimpleTimer library. So Karma provides us with simply using this and it to works.

        So it can play music while being a web server, simultaneously. Pretty nifty for a quick hack, on an 8 bit.

        One issue was that I needed to lower the Timer Period from 250 to 125 to play a 192K encoded file. Makes sense and not much of an issue.

        But the Carson Daly effect; reveals that now it is main loop polled and not interrupt driven the Music pauses when the web server is accessed. A minor draw back. Considering it is all a quick hack.

        Not sure if there is a better Ethernet Driver? that does not interfere with unused interrupts.

        Just need to tweak the code to play files from the web page requests.

    • FlagaNo Gravatar says:

      Time for the next level?

      I am interested in making an improved MP3 shield, with several new features I have come up with, not available on the current shield. That I have from my own projects.

      Is there any interest? I am fancying a KickStarter project. May be targeting a 100 pieces.
      Are there any request for new features?
      Any suggestions or thoughts are welcome?

      • JamesNo Gravatar says:

        Yes, do it 🙂

        Line level outputs, along with headphone level – could be handy. I have line levels as per their recommended app note design, and it works well, and works with headphones too just at a reduced volume.

        Nothing wrong with this library by any means, but if you are going to be releasing a new one with ‘more’ stuff, that would be great.

        I have implemented, forward, back, pause, random (doesnt repeat a song till all are played), continuous (plays songs one after the other, or plays just a single song once).

        Would be great to get proper bitrate info out from the VLSI chip, as per the VLSI forum link I put above, and the ability to stream song position would also be nice once bitrate is sorted. Just simple things that ‘commercial’ type MP3 players have as basic funcationality.

        Ability to play WAV, MP3 etc (which I know is already supported), so when it goes to next song, it doesnt care if its WAV or MP3.

        Input stuff I dont personally use, but there are a ton of people who do use the audio input stuff on these chips.

        Have you looked at the other offerings on the chip range? 1063 for instance? I dont know what they changed, I havent actually looked in detail.

        They are impressive chips with lots of features not utilised.

        I would pledge to your kickstarter, even though I dont really use shields or the arduino form factor, I generally build my own in the format I want. But having one to play with could be cool.

      • JamesNo Gravatar says:

        You could even have a dedicated on board processor if you were really that way inclined, take the overhead off the ‘Arduino’ processor, which may be doing much more than just playing MP3’s.
        You could even have the comms between the two processors over I2C or SPI even, so you dont use up the Arduino’s serial port.

        Dunno. lots of options, im sure you have the hardware sussed in your mind anyway.

        I personally have my custom board with a 1284P next to the VLSI chip, dedicated to playing the Arduino. 1 serial port dedicated to talking to a car ECU, and the other dedicated to talking to a 4D Systems intelligent touch display, for showing all the MP3 info/interface, and doing datalogging of the car ECU, information etc. Working great.

        No doubt people who use these shields want to be controlling stuff other than the MP3 player, so having an on board processor to free up the Arduino, im sure would be handy. They might have more SPI devices on the Arduino and dont want them killing the MP3 stream or vice versa.

        Many options 🙂

        • BillNo Gravatar says:

          In regards to on board processor, your talking about doing our own version of this. I’ve used two of those boards and don’t like it. Mainly because it’s closed source so I couldn’t fix a bug that was effecting my project nor could I add a simple feature I needed for another project.

          So I would like to see an open version of the ‘mp3 trigger’ and I’d definitely back a project to make one. It’s been one of dozens of back burner projects to do myself, but like all of them the are overshadowed by my up-coming wedding.

      • CameronNo Gravatar says:

        with the arduino due released is there much point??? the cortex M3 has decoding abilities built in, is there any advantage of this over running a single M3 chip with a good sound library???
        p.s. i still plan on finishing my current mp3 project, designing a PCB to put a 328, the mp3 decoder, micro sd and lipo monitoring/charging circuitry all on a single board as a pocket sized mp3 player, with a capacitive touch screen. long long way off that yet tho 🙁

      • BillNo Gravatar says:

        Let me know if you need any help with hardware design. I’m better with hardware then I am with software.

    • FlagaNo Gravatar says:

      Same here. About HW vs SW. I’ve designed a lot of PCB for employers (at these quantities) I always find more eyes is better. Started with a HC08 and assembly, but since left coding to teams while on the 32bits. I have enjoyed very much this experience in getting back into programming. And think there may be a need I(we) can address.

      I am not fixed into any hardware yet, it is quick for me to plop and change things. Just fielding a Blue Sky research… I am thinking of a new PCB, that would be compatible with this library.
      Maybe a Arduino Pro MP3 (combo single PCB: e.i. 328(or/1284/2560)+SD+VS1053) is a good idea. Seems like a lot to squeeze on one Arduino size board.
      I see Hellebuyck’s KickStarter for a battery shield. That may mitigate a need for Battery. But I have actually done the LiPo on my PCB. So I could make a shield for that too. As I seen some flaws in SFE break out, actually blown it up.
      Line Levels. Not sure what you(James) are looking for, that is different. I use both line and headphones and don’t notice a need to reduce level. (I might have not noticed it, either.) I have been using line input on my PCB for mixing in; and could add microphone support easily enough. Think … Karaoke-duino (needs some help on that name).
      Buttons for Arduino record and play-back. Need to add recording to the Library.
      Support for the Mega, like the Ethernet shields do with the ICSP. Along different interrupts inputs.
      VS1063 is a good idea to think about, think forward. I do notice it is priced more $12EU vs $8EU for 100 pcs. VLSI claims it is drop in compatible. The big thing I see it offering is recording MP3, the 1053 only records OGG,PCM(wav) along with G.711 support. Which is typically used in VOIP and internet streaming. May be an internet radio. But there is a plugin for G.711 on the 1053.
      I have seen hints that the VS10x3 can load data directly from the SdCard, if wired correctly.

      I have been making attempts at getting bit rate and position, as to properly support fast forward and skipping. But no joy yet. But this is a soft library thing.

      There is always a tossup of what is coming around the corner versus now and supporting what works. I often let the “why bother” concept stop me. Then later wishing I had followed through. And there is always a strong need for things that are simple, where currently the Arduino and VS1053 is such an example. I have actually purchased the Olimex MP3 board with the M3 core. But find the only libraries are written in IAR compiler and that is bit expensive. Let alone for any novices. I am sure the Due will change the market. That said the VS10x3 DSP’s are a fully featured chip and supports development of its own loading from EEPROM over SPI. Where the Arduino itself is not really needed.

      I think there is some fun to be made here.

    • BrianNo Gravatar says:

      I just wanted to know before I got into this library if it supported the ability to get the name of the currently playing track as well as to enumerate the tracks on the SD card. If there are tags on the MP3 can I get at them while a file is playing on the shield?

      • FlagaNo Gravatar says:

        Yes, it can printout the Title, Artist and Album. Provided the track has the Tag ID filled in. Which is often not initially in the MP3 files. But there are 3rd party software that will do this. I recall doing it to many of my tracks. The example INO will print out what it finds. Could be garbage if the ID tag is not filled in. Others may have input on this. The getTrackInfo() should get the requested info while playing and return back to that pointer, quickly before more data is needed.

        As for enumerating. Yes, it can be done, not hard to list them out. This is a function of the SdCard Library and not this library. The trick is to list them out and then provide a way to select from that list, in less than 600 bytes that are left. Methods have discussed previously in this forum. Note this core library is not yet providing much in complete jukebox examples of a complete application. Rather providing examples of the basics. As to empower individuals to contrive their own inventions. All the pieces are all there.

        That said I am close to making a web based variation that will play from a list of files.

        • BrianNo Gravatar says:

          Thanks for the reply. The web based version sounds interesting. I work with a haunted house and building a web based control system for our house audio and Fx would be really slick. I would love to know when you finish this so i might be able to check it out.

    • jimmyNo Gravatar says:

      I made the mistake of picking up a Seeed Music Shield in a local shop. I should have waited and ordered a proper one on-line.

      No working code or Docs. So I’m trying to adapt this library.

      I’ve got the SD library working, and I’ve got my pins set up thusly:

      #define MP3_XCS A3
      #define MP3_XDCS A2
      #define MP3_DREQ A1
      #define MP3_RESET A0

      #define SD_SEL 10

      But I can’t figure out how to set up

      DREQINT

      So when I try to play track 1 I get maybe the first second or two of audio (maybe repeated twice, not sure)

      Michael, i tried to grab some of your branches where you were looking at Timer1 firing the interrupt, but I couldn’t figure out exactly how that was meant to work. Your comment says Timer1 interupt on pin2, I think?

      Anyway, if anyone has any ideas for adapting this LIB to other boards, I would appreciate it.

      Thanks!

    • Michael P. FlagaNo Gravatar says:

      I have completed an extensive enhancing of the Arduino SFEMP3Shield library and have pushed it up to both Bill’s and my repositories. Labeling it Release 1.0.0

      This new release contains several solved gremlins and newly requested features. Along with support of different hardware by means of refilling either by timers or interrupts. Finally Bit Rate is now read directly from the VS1053 itself. Notice you can actually increase the play speed and turn on Head Phone Spatial effects.

      Most notable effort was in creating supporting documentation and trouble shooting. Many of the questions asked on the forums where directly exampled in the new menu features. Along with a printing of the SdCard’s directory listing.

      Extensive support can be found at GitHub project page http://madsci1016.github.com/Sparkfun-MP3-Player-Shield-Arduino-Library/ along with trouble shooting of common problems. As the code has been written with plenty of insightful comments, describing key components, features and reasoning’s in Doxygen markdown style as to directly auto generate html supporting documentation. Which can be found at GitHub project page . Please read through this document and referring linked resources. As it contains additional resources

      Please refer all supporting questions to Bill’s new support forum http://www.billporter.info/forum/forum/sparkfun-mp3-shield-support-forum/

      • mgrusinNo Gravatar says:

        I’m excited to see the updates to this library (which we’re big fans of at Sparkfun), but the files section of the above Github link show 404s for all the files. Could you take a look? Thank you!

        • Michael P. FlagaNo Gravatar says:

          I believe you are referring to the Doxygen output on the GitHub Pages’ file tab. If so..

          Fixed it.
          Otherwise please point the way.

          I was bummed when I pushed out the gh-page branch late last night (novice at Doxygen and gh-page) and saw that. So it was not just me, kind of hoping, but knowing otherwise. And you have confirmed that.

          So a day later, since it was noticed and a little Google Foo, I have found that gh-page’s jekyll is on by default and was dropping pages with leading underscores, that were created by Doxygen. A touch of “.nojekyll” file solves that, preventing jekyll on that branch.

          I hope this library helps, your customers. We have seen many posts from them here.

    • stiekje57No Gravatar says:

      MP3 Player Shield from sparkfun runs on Leonardo ??

    • JensaNo Gravatar says:

      Thanks a lot for your work on this library!

      I just wrote up a small guide for making it work with the Gravitech MP3 Player add-on (or rather shield?) for Arduino Nano as well:

      http://flashgamer.com/arduino/comments/tutorial-making-gravitechs-mp3-player-add-on-work

      Hope it’ll be of use for others! 🙂

      J

    • mgrusinNo Gravatar says:

      Hi Michael, where (here, forum, issues at Github) is your preferred location for feedback on the new library?

      Thanks! -Mike

      • Michael P. FlagaNo Gravatar says:

        Any place, If I see it I will likely respond to it.
        Bill’s WP comments has been the most visited, but overloaded. Hence he created a WP support forum for requests and alike.

    • UC372044No Gravatar says:

      Hi Bill!
      Thank you so much for the libraries it helps a lot!
      I’m facing a problem while using sparkfun mp3 shield on top of a Seeeduino Mega (mp3 shield directly stack onto Seeeduino Mega).
      Verification and upload of the MP3Shield_Library_Demo provided are just fine.
      But on the serial monitor it shows:
      “Free RAM = 6623 Should be a base line of 1007, on ATmega328 when using INTx
      Error code: 1 when trying to start MP3 player …”
      Referring to the error codes its SdFat initiate problem, and I’ve tried using different SdCard and the same error occurs.
      What should I do to troubleshoot this problem? Would really appreciate if you could guide me to overcome this problem. Thank you in advance!!

      • Michael P. FlagaNo Gravatar says:

        Have you had a chance to look at the trouble shooting guide. http://mpflaga.github.com/Sparkfun-MP3-Player-Shield-Arduino-Library/ . Support for the mega is specifically detailed. I would initialy suspect it be the same for seeeduino mega. Search the docs for mega, detailing issues and work a rounds.

        If you are still having problems please look at and/or submit an issue in the support forum http://www.billporter.info/forum/forum/sparkfun-mp3-shield-support-forum/

        Let us know if the support page solved your issue. Confirming seeeduino mega. Or if their is any issues needing to be added.

        • UC372044No Gravatar says:

          Thank you! The support page does help!
          Tried the troubleshooting guide u provided, jumpered the required pin, verify and load, no more “error code 1”! and the Sdcard verified able to be read! then another error occur…
          “Error code: 6 when trying to start MP3 player”
          checked the error code, it is about “Patch was not loaded successfully”, why do this happen? What does the patch means and how should I troubleshoot this?

          • Michael P. FlagaNo Gravatar says:

            I have updated the support with the following explaination.

            The VS10xx chips are DSP’s that run firmware out of RAM, that is loaded from ROM at boot time. The ROM is internal to the VS10xx chip itself. Where the VSdsp’s RAM can additionally be loaded with externally provided firmware, also known as patches or plug-ins, over the SPI port and executed. This allows the VSdsp to have a method for both fixing problems that may exist in the factory ROM’s firmware and or add new features provided by VLSI’s website. It is even possible to write your own custom VSdsp code, using there Integrated Development Tools (VSIDE).

            \note patches.053 is a cumulative update correcting many known troublesome issues.

        • UC372044No Gravatar says:

          Oh I forgotten to put plugins into the root of SD card, “error code 6” fixed!
          Then now…
          “Error code: 2 when trying to play track”
          Check from the guide, it refers to “File not found”, but when I verify the SD card using ‘d’ function, it shows my mp3 file was in there, why is this happen?

        • UC372044No Gravatar says:

          File naming problem!
          It Works!
          The code work for Seeeduino Mega using the pin configuration provided for Arduino Mega!
          THank you so much!

    • nonlinearmindNo Gravatar says:

      I’m having trouble increasing the volume in my sketch. I don’t need the volume to be adjustable. Just as loud as possible. What line of code would I insert to get the volume cranking (like to 11)?

    • AlexNo Gravatar says:

      Great project!

      But function skipTo is not working for me (((

      It’s always jump to beggining of the file.

      Not to the position in ms.

      It’s so sad (((

    • Michael P. FlagaNo Gravatar says:

      Thanks Alex for pointing that out.
      I have moved your bug to the forum. http://www.billporter.info/forum/topic/bugs-and-feature-fixes/#post-1746

      Please check for up dates as for the fix.

    • M. HelioNo Gravatar says:

      Just wanted to mention that this library works out of the box without a single modification when using Sparkfun’s Pro micro wired to the shield. Thank You for this awesome library!

      • Michael P. FlagaNo Gravatar says:

        Thanks for the feed back.

        I would mention that SparkFun Pro’s are available in both 3V and 5V and the SFE MP3 Player Shield requires 5V.
        Where your Pro Micro requires wiring, anyways and I am glad it worked. I have had to hack my Shield to support 3.3V shields.

        I will add to the to do list commenting as such in the documents.

        • M. HelioNo Gravatar says:

          Oh, completely forgot to mention that that the Pro Micro is 3.3V/8MHz version and the shield is hacked basically just removing the level converter. (I was so stoked while writing the earlier comment =)
          I’ll keep testing and see if any problems arise, possibly start working on a Micro-sized shield since it seems to be only a question of form factor.

          • Mike GrusinNo Gravatar says:

            Mike from Sparkfun here, just wanted to note that Sparkfun’s MP3 Shield works at both 5 and 3.3V (when using 3.3V, the level converter effectively becomes a pass-through). I’ve extensively used the shield and a 3.3V Pro with no problems.

            • Michael P. FlagaNo Gravatar says:

              The problem I had was with the 5V to 3V regulator on the shield. I specifically had a MegaPro3.3V and the 3.3V after the LDO was too low for the VS1053. In my case the VS1053 failed to initialize. The LDO may also cause intermittent issues if left untreated. This may vary between instances and loads, etc…

              I simply shunted its input and output and it runs fine. No problem with the level shifter.

              Either way, in the spirit of the late Bob Pease (snip snip) it can be made to work.

    • Michael P. FlagaNo Gravatar says:

      You may want to look at previous comments in this thread about Gravitech’s mp3 shield for the Nano.
      Where as I see the SFE Micro and the nano are not equivalent pin out.

Leave a Reply

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