earlephilhower / ESP8266Audio

Arduino library to play MOD, WAV, FLAC, MIDI, RTTTL, MP3, and AAC files on I2S DACs or with a software emulated delta-sigma DAC on the ESP8266 and ESP32
GNU General Public License v3.0
1.98k stars 432 forks source link

mp3 won't work #651

Open BimoSora2 opened 8 months ago

BimoSora2 commented 8 months ago

mp3 won't work

#include <Arduino.h>
#ifdef ARDUINO_ARCH_RP2040
void setup() {}
void loop() {}
#else
#include "AudioFileSourceSD.h"
#include "AudioGeneratorMP3.h"
#include "AudioOutputI2SNoDAC.h"

//SD Card Pins
#define SCK 5
#define MISO 6
#define MOSI 7
#define CS 8

// For this sketch, you need connected SD card with '.flac' music files in the root
// directory. Some samples with various sampling rates are available from i.e. 
// Espressif Audio Development Framework at:
// https://docs.espressif.com/projects/esp-adf/en/latest/design-guide/audio-samples.html
//
// On ESP8266 you might need to re-encode FLAC files with max '-2' compression level 
// (i.e. 1152 maximum block size) or you will run out of memory. FLAC files will be 
// slightly bigger but you don't loose audio quality with reencoding (lossles codec).

// You may need a fast SD card. Set this as high as it will work (40MHz max).
#define SPI_SPEED SD_SCK_MHZ(40)

File dir;
AudioFileSourceSD *source = NULL;
AudioOutputI2SNoDAC *out = NULL;
AudioGeneratorMP3 *decoder = NULL;

void setup() {
  Serial.begin(115200);
  Serial.println();
  delay(1000);

  audioLogger = &Serial;  
  source = new AudioFileSourceSD();
  out = new AudioOutputI2SNoDAC();
  decoder = new AudioGeneratorMP3();

  // NOTE: SD.begin(...) should be called AFTER AudioOutputSPDIF() 
  //       to takover the the SPI pins if they share some with I2S
  //       (i.e. D8 on Wemos D1 mini is both I2S BCK and SPI SS)
  #if defined(ESP8266)
    SD.begin(SS, SPI_SPEED);
  #else
    SD.begin();
  #endif
  dir = SD.open("/"); 
}

void loop() {
  if ((decoder) && (decoder->isRunning())) {
    if (!decoder->loop()) decoder->stop();
  } else {
    File file = dir.openNextFile();
    if (file) {      
      if (String(file.name()).endsWith(".mp3")) {
        source->close();
        if (source->open(file.name())) { 
          Serial.printf_P(PSTR("Playing '%s' from SD card...\n"), file.name());
          decoder->begin(source, out);
        } else {
          Serial.printf_P(PSTR("Error opening '%s'\n"), file.name());
        }
      } 
    } else {
      Serial.println(F("Playback from SD card done\n"));
      delay(1000);
    }       
  }
}
#endif