ESP32 Becomes Music Player In Under 40 Lines Of Code

The demo code for [XTronical]’s ESP32-based SD card music player is not even 40 lines long, though it will also require a few economical parts before it all works. Nevertheless, making a microcontroller play MP3s (and other formats) from an SD card is considerably simpler today than it was years ago.

Part of what makes this all work is I2S (Inter-IC Sound), a format for communicating PCM audio data between devices. Besides the ESP32, at the heart of it all is an SD card reader breakout board and the MAX98357A, which can be thought of as a combination I2S decoder and Class D amplifier. The ESP32 reads audio files from the SD card and uses an I2S audio library to send the I2S data stream to the MAX98357A (or two of them for stereo.) From there it is decoded automatically and audio gets pumped though attached speakers.

A few economical components, and only a handful of connections between them.

It’s amazing how much easier audio is to work with when one can take advantage of shuffling audio data around digitally, and the decoder handles multiple formats with an amplifier built in. You can see [XTronical]’s ESP32 player in action in the video embedded below.

Intrigued by I2S and want to know more? You’re in luck, because we covered everything you’d want to know about I2S and how it works.

59 thoughts on “ESP32 Becomes Music Player In Under 40 Lines Of Code

  1. Yeah, 40 lines of code. Plus about 12000 lines of code in the library that actually does the job (checked their github).

    Someone did that work and shared it – so technically now you need 40 lines of code, yes. But headers like this kinda devalue all the work done by those people – instead of appreciating another great effort, they create an illusion that it’s something very simple.

    1. This

      I cringe everytime I see someone on the internet making something, only to discover that they’re using Arduino. Then they import a random library, and finish their 3 lines of code with DoStuff.begin().

      Look I get the whole point that its “not-for-professionals” and “only-for-education” tool or whatever. The thing is, its a bad tool even for education. There is no education happening whatsoever. Connecting a few wires to breadboard may be educational for 8 year olds, but anyone older? I doubt it. Its sad to see colleges teaching courses using Arduino these days.

      Just look at this project. What has the average person who followed the tutorial learned? What is an I2S bus? What toolchain is he using? Can anyone even point towards the datasheets of the parts they are using? Interfacing with an SD card is a complex task, are they using the SPI bus or SD interface? There was no information about this at all.

      I agree though, its a great tool for someone who wants to get something done, without diving too deep. But lets also stop pretending that its for “kids” or “education”.

      1. I disagree about it being a bad tool for education. I, myself, began learning about electronics with an ESP8266 and the Arduino-core for it and I learned how various kinds of buses work, including I2C and SPI, learned how one can modify the various built-in peripherals’ operation via memory-mapped registers, I learned how to read specsheets, I bought a good bunch of various modules and figured out how they function from the hardware point-of-view and so on and so forth.

        You harping on about how the project here doesn’t go into depth and explain every single little thing and isn’t an all-encompassing guide on electronics is entirely missing the point as well.

        1. “just imagine some company wants to hire a hardware/software guy (or a gal) and they read their cvs”

          That”s a very strange CV. I’m currently job hunting and writing cover letters on a daily basis. When was the last time you applied for a job? In the 80’s?

      2. I agree that the title is miss-leading, however this video was titled as a “Quickie”, designed to have just enough detail to get it going. In the previous video in this series I go into some detail about I2S (hey, even animations and everything!), where I cover the same library using it to access web streams. The SD card is also covered there, I wasn’t going to repeat that all over again (it would not be good viewing for subscribers to have that all repeat) and I point the viewer to that information early on in the video with a link in the description.

        1. I want to have something like this that plugs into the CD changer connection in late 90’s to early 00’s Ford vehicles and is controllable with the head unit’s CD player controls. They were 6 disc changers and a CD allows for up to 99 tracks, so the SD card would need 6 directories, each of which could have up to 99 audio files. 594 songs. There aren’t 594 songs that I like. One card with all my favorite music in my 1997 Ford Taurus and I’d be set, and nobody would be busting a window to steal anything.

      3. This kind of blanket dismissal of the value of easy to use systems and platforms as a part of a valid educational strategy convinces me mostly that you have never stood in front of a room full of undergraduate art and design students with an interest in incorporating code and hardware into their practice.

      4. Yeah I really hate how kids these days just pick up a piece of aluminum and start making 3d printers with it rather than learning how to refine bauxite by refluxing it with sodium hydroxide and then melting it in cryolite and reducing it using carbon electrodes. They know nothing, NOTHING!

        Where I work, our IC designers use arduinos to provide complex stimulus patterns to the FPGA models of our new designs. They _write_ the chip datasheets.

          1. LOL. I have been there. I was working as a software engineer together with IC designers, and decided to learn verilog so I could understand their code, and also write small verilog modules for testing my firmware in simulation. I could have asked the h/w guys, but they were always too busy to help me, so I decided it would be quicker if I just did it myself.

            Then I realized it was fun, so I got myself an FPGA board to play with at home.

      5. Back in the ’90s, I laid out circuit boards for 8051 microcontrollers and miscellaneous support chips, etched them, soldered on all the parts, compiled the code on a PC, burnt it to an EPROM and inserted it into the board to see if the code worked. I wrote everything I needed in assembly with no pre-written libraries. You know what? Today I would just as likely use an Arduino, or some other pre-built board and just get to making things work. It’s no different than using a microcontroller IC rather than building your processor from 7400 series chips. Or using 7400 chips instead of discrete transistors and resistors. Or using commercially manufactured transistors rather than refining your own silicon and building your own fab. “If I have seen far, it’s because I have stood on the shoulders of giants.” There’s no need to reinvent the wheel every time you need one just to prove that you can, just build what you want.

      6. No, you haterz are off the mark. Simple projects are a gateway drug. When someone is able to follow simple instructions, make a few connections, copy/paste and compile a small page of code… and it works, they’re hooked. They will start to think about changes and improvements, they will learn more about the bits and the code, they will try things, make changes…

        For me it was Remco electrical panels with lights, switches and buzzers, and later a 50-in-1 electronics kit. For today’s n00bs – Arduino. It’s all good.

        1. Exactly this. I’m just getting started with the ESP32 because of another user’s contributions. (ESP_8_BIT) Sure I’m just knocking rocks together and hoping at this point, but I learned about flat file systems and SPIFFS fixing my troubles. It’s new info to me and I wouldn’t have found out with a relatively unintimidating project to start.

          Copypasta shows people that it’s not magic and that they can learn it.

          Right now I’m trying to see if I can setup persistent Bluetooth pairing, and I literally don’t know anything about that yet. Why? Because I want to improve the turnkey project that I’ve been learning from.

          Old hands shouldn’t gripe about low hanging fruit for newbs to get started with.

        2. Bingo. I am an ME by education. I stumbled onto this site a couple years back along with and now have learned rudimentary digital logic and am building my own circuit boards. I am also attempting to learn FPGAs. All this is way outside my comfort zone, but I have learned a ton and my life will never be the same. We all have to start somewhere. If an Arduino works, it works. Perfect is the enemy of good enough (in the real world).

      7. I cringe every time I hear people complaining about Arduino. It’s a wonderful tool for education. May I add, I have a degree and years of experience in teaching. I even taught Arduino programming. I kindly ask you to shut up about education unless you are an educator yourself (clearly not).

        1. If you can read datasheets and are able to interpret Arduino code, you just might be able to learn programming bare microcontrollers without too much trouble.

          I think Arduino is a great platform to get your feet wet enough to continue to other languages.

          Also, why bother creating all new code from scratch when you can just take a ready built platform and write some code to get it working. After all, this is Hackaday, not “How to create the best code to use in a commercial product.”. I know how to program AVR microcontrollers, 8051 CPUs, but just like to use something easy if I want to get things done quickly.

      8. 100% disagree. Not everyone technical has an EE degree. Your idea of learning may not someone else’s and if an Arduino solves ‘their’ immediate problem than what is the big deal?

    2. +1

      Going to the moon isn’t difficult either, it only takes one person pushing only one button… it’s really easy you should try it (that was sarcasm for those who didn’t notice).

      Simplifying things is important, but in the case of Arduino things are simplified beyond recognition, the important parts are very well hidden under the hood of something called a library, which you can call like a black box, no knowledge required if you just follow the example. But on the other hand, sometimes this is just what you want. If you want to be creative and make things based on existing things, why reinvent the wheel, shielding technical details. Technical details that most people can’t comprehend or don’t even want to know about. This can be a good thing for progress.
      Though on the other hand, not knowing how things work, can lead to hideous design where people do the most technologically advanced stuff (without realizing it) and use effectively high end equipment for a simple task. Just because you can blink an LED with only 6 lines of code doesn’t mean it is the correct approach to blink an LED. Though if it works and everybody is happy, then what’s the problem, but I for myself, I know I would do it different.

      But I’m not worried about the future, people who don’t care what’s in the library, aren’t the people we need for a technological advanced future. The people who do want to know the technical details, are smart enough to figure out what’s inside the library. And If it takes 40 lines of code to play a sound file (which can be done with less if you are willing to shuffle uncompressed sample data and use a simple R2R DAC and some memory to store the samples), then this is a good thing. As it is a good way to get people acquainted to an environment in a very simple way. No need to read datasheets (if you don’t want to), just do your things and figure out the details later (if you want). Arduino is a great way to introduce micro-controllers to young people.
      As a side effect of the Arduino success, sensors and everything else you can connect to this has become widely available is easy to use form factors and is dirt cheap. So although “only 40 lines of code” is a complete lie (we may call click bait), it does have some value. Personally, the ESP8266 loured me into the arduino environment and this in term seduced me to try out the Arduino Pro Micro, this allowed me to cut some corners in very playfull (not serious or commercial) projects, this would otherwise costs me much more time to do it right using conventional micro-controllers and designing my PCB and code from the ground up, just to optimize, for a one time project it sometimes
      just isn’t worth it and the arduino, it’s environment and it’s community can be a great tool to have.

      But, 40 lines of code… yeah, sure if that’s what you want to believe, feel free to do so.

      1. HaD would editors would say “Repurposed red button sends Men to Moon”. They dehumanizing of the efforts of people is pervasive in their headlines and descriptions. “Arduino balances robot and detects hungry cats” type stuff. Really irritating. Never “Bob’s Arduino code …..”.

    3. I do not know why I even bother to reply to this but….. Stop whining and all go back to you 7400 TTL chips homemade processor and program on your hex keyboard. I have been there and done that and I think this is a great time to build projects.
      It is incredible to have libraries available for everyone to build the most amazing projects with just a few lines of code. Just like it is amazing to have a processor available that does the things you need 200 or so 7400 series IC’s for.

    4. There’s always one person that has to be that guy. Don’t be that guy. We get it.

      Unless you built your own house and/or personally send Christmas cards to the people that built your house every year just shut the hell up already. FFS.

  2. this is the setup im going to use in my mk3 raspberry pi tablet. mk2 did it with an amp on the audio jack output, and the sound was rather kvlt. the speakers were el chepo ebay speakers in 3d printed inclosures, using the old wing-it design philosophy (never buy speakers with no datasheet), so this time im going with speakers that come built into pre-engineered enclosures.

  3. That’s nothing, I can send people to Mars and back with 2 lines of code:

    #include “allthestuff” //25 million lines of code in here
    void main(){allthestuff.begin();}

  4. I did something like this like ten years ago but the other way round: ADC for Audio with S/PDIF output.
    It used an PIC 18F which ran around 1000 lines of assembly code, even so most of the code was used for a config menu on an lcd display.
    Most of the ‘heavy’ data was just handed from one IC to another.

  5. So then, how long before we start calling the environment arduinOS and say your main prog is just a fancy autoexec.bat to call up apps that accept complex arguments, that are mis-named as libraries.

    1. It is really about leaving humans completely out of descriptions. In the history of HaD I can’t recall a single balancing robot story that actually mentioned where the algorithms came from or who wrote/derived them. HaD is more like the Drudge Report with links to abbreviated versions of whatever happened and you can get some ideas on how to search for more info. Or links to Github where you can look at code headers to see where libs or other sources came from. It generally takes a lot of work to find the real info behind a story.

  6. What, no “not a hack” comments? I’m seeing a lot of complaints about neglecting the fact that much of the work was already done by someone else, but what is the nature of a hack? To me it’s always been take some preexisting stuff and put it together in a way to suit your needs and add something of your own, and hopefully learn something along the way (this regulator doesn’t work, needs a capacitor, etc.).
    Recording the process and what you learned makes it viable for consumption here.
    This is not ” Gain all the knowledge equivalent to matriculating from the college of the discipline required to build something-a-day”. And while this build might be quite effective for someones needs, I would find it lacking and would want to learn more in order to give it a usable display interface, file playback ordering, Proper ID3 cataloging, etc. But it’s a good stepping stone for someone.
    Agreed, the title is like saying “Build an airplane with only 2 parts” (air frame + engine), but hacks are not built from scratch. If you mine, smelt, cast and forge the metals, then build to an original design, you’re certainly talented and creative, but it’s not a hack. If you build a plane from parts scavenged straight from the aviation scrapyard, and the parts all come from different models, or a non aviation part or two in the mix, definitely a hack. All of the complaints will come from the aviation aficionados regarding it’s safety, and why it was irresponsible to even post it. But I doubt anyone would complain about the lack of credit to the Wright brothers.
    This particular post may seem critically flawed to the Arduino crowd, and it’s “Hack” status may seem dubious, but, for those without the prior knowledge, the title still stands, and the gateway for learning is open.

  7. Did not see it mentioned yet: there is an espressif board (family) that does exactly this: the esp32 lyra-t. It is a demo board for bluetooth speaker applications. Of course there is demo code for that too, so to keep in line with this post, that’s zero lines of code you need to write…

  8. I think we are forgetting that the articles written here are assumed to be consumed by an audience that will be technically savvy to the point that they’ll realize that an MP3 decoder is probably not included in that 40 lines of code. I too feel a bit crusty towards kids that bang on how they created something pretty novel finding out that it was hacked together in an afternoon with no deeper knowledge than they included a library that handled all the detail—so yea I get it, sometimes they act like they invented sex or something.

    I don’t think it’s a bad thing thing that you can pull together these libraries and build something this complex so quickly and carelessly. It’s awesome that anyone with basic programming skills can throw something together and have it work. Python seems to have this same reputation. Next generation will have ultra simple programming interpreter running legos that all interoperate without knowing anything about electrical interconnects or APIs. They’ll feel picked on by graybeards harping on how they had to compile things on their arduinos and had to cut and paste code in a stupid ide.

    1. This.

      Even though I’m a curmudgeon in my own practice, I have to admit that it’s a sign of how successful/useful the various libraries are when someone can “write X in N lines”. After all, if you think of all the crazy things you can do with a single “line” in a modern operating system…

      But counting lines of code never makes any sense anyway. It’s machine instructions or get off my lawn. Anything else is just too many layers of turtles to make comparison valuable.

    1. As an aspiring maker myself, it becomes clear that everybody had to start somewhere and over time, the environment changed, the ways the older generations think did not.
      Reminds me of the debate that teaching microcontrollers to kids is a waste of time,
      concepts for
      Machine Learning
      Artificial Intelligence are the way to go.
      I must say, whoever says that has a point, but you have to start somewhere, but learning everything makes no sense either.

      Most people learn just enough in their profession that everything works “good enough”. The last 20% to achieve the perfect solution cost considerable more effort and often don´t pay off. For some people this may sound heretic and they also have a point, but I can assure them, whenever we need the perfect solution, they will be asked for their services. It is just a rare occassion that we need this.

Leave a Reply

Please be kind and respectful to help make the comments section excellent. (Comment Policy)

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