ESP32 audio mp3 playback

Templas
Posts: 1
Joined: Fri Jan 21, 2022 9:39 pm

ESP32 audio mp3 playback

Postby Templas » Fri Jan 21, 2022 9:51 pm

Hello.
I am trying to set up a new bell for the school I work in. I would like the esp32 to play different mp3 songs stored in an sd card. I have been trying to, at least play a different 10-second file to try at least to be able to change song and play it at a certain time. After a reset, it plays the song. After that it is impossible to make it play again. I am using an esp-wroom-32, a pcm5102A and an sd card reader. I am a bit desperate after several days.
Thanks in advance for your help.

The code is this:


#include <WiFi.h>
#include "time.h"
#include <WiFiClient.h>
#include <WebServer.h>
#include <ESPmDNS.h>
#include <Update.h>
#include "Arduino.h"
#include "Audio.h"
#include "SPI.h"
#include "SD.h"
#include "FS.h"

// Digital I/O used
#define SD_CS 5
#define SPI_MOSI 23
#define SPI_MISO 19
#define SPI_SCK 18
#define I2S_DOUT 25
#define I2S_BCLK 27
#define I2S_LRC 26


Audio audio;

const char* host = "esp32";
const char* ssid = "xxxxx";
const char* password = "xxxxxxxxx";

const char* ntpServer = "time.google.com";
const long gmtOffset_sec = 3600;//Diferencia de zona horaria en segundos.
const int daylightOffset_sec = 7200;//Diferencia en horario de verano en segundos.
int ano, hora, minutos, segundos, diaMes;
int *ptr_hora = &hora, *ptr_diaMes = &diaMes;
byte diaSemana;
byte byteMes;
boolean interruptor_poner_en_hora = HIGH;
byte comprobadorCambioHora = 0;
byte comprobadorDiaMes = 0;

WebServer server(80);
/*
* Login page
*/
const char* loginIndex =
"<form name='loginForm'>"
"<table width='20%' bgcolor='A09F9F' align='center'>"
"<tr>"
"<td colspan=2>"
"<center><font size=4><b>ESP32 Login Page</b></font></center>"
"<br>"
"</td>"
"<br>"
"<br>"
"</tr>"
"<td>Username:</td>"
"<td><input type='text' size=25 name='userid'><br></td>"
"</tr>"
"<br>"
"<br>"
"<tr>"
"<td>Password:</td>"
"<td><input type='Password' size=25 name='pwd'><br></td>"
"<br>"
"<br>"
"</tr>"
"<tr>"
"<td><input type='submit' onclick='check(this.form)' value='Login'></td>"
"</tr>"
"</table>"
"</form>"
"<script>"
"function check(form)"
"{"
"if(form.userid.value=='admin' && form.pwd.value=='nimda')"
"{"
"window.open('/serverIndex')"
"}"
"else"
"{"
" alert('Error Password or Username')/*displays error message*/"
"}"
"}"
"</script>";

/*
* Server Index Page
*/

const char* serverIndex =
"<script src='https://ajax.googleapis.com/ajax/libs/j ... '></script>"
"<form method='POST' action='#' enctype='multipart/form-data' id='upload_form'>"
"<input type='file' name='update'>"
"<input type='submit' value='Update'>"
"</form>"
"<div id='prg'>progress: 0%</div>"
"<script>"
"$('form').submit(function(e){"
"e.preventDefault();"
"var form = $('#upload_form')[0];"
"var data = new FormData(form);"
" $.ajax({"
"url: '/update',"
"type: 'POST',"
"data: data,"
"contentType: false,"
"processData:false,"
"xhr: function() {"
"var xhr = new window.XMLHttpRequest();"
"xhr.upload.addEventListener('progress', function(evt) {"
"if (evt.lengthComputable) {"
"var per = evt.loaded / evt.total;"
"$('#prg').html('progress: ' + Math.round(per*100) + '%');"
"}"
"}, false);"
"return xhr;"
"},"
"success:function(d, s) {"
"console.log('success!')"
"},"
"error: function (a, b, c) {"
"}"
"});"
"});"
"</script>";

void setup(){
pinMode(SD_CS, OUTPUT); digitalWrite(SD_CS, HIGH);
SPI.begin(SPI_SCK, SPI_MISO, SPI_MOSI);
SPI.setFrequency(1000000);
Serial.begin(115200);
SD.begin(SD_CS);
delay(1000);
if(WiFi.status() != WL_CONNECTED){
WiFi.disconnect(true);
}
audio.setPinout(I2S_BCLK, I2S_LRC, I2S_DOUT);
audio.setVolume(12); // 0...21
audio.connecttoFS(SD, "320k_test.mp3");
// Connect to Wi-Fi
conectar_wifi();
// Init and get the time
configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);

/*use mdns for host name resolution*/
if (!MDNS.begin(host)) { //http://esp32.local
Serial.println("Error setting up MDNS responder!");
while (1) {
delay(1000);
}
}
Serial.println("mDNS responder started");
/*return index page which is stored in serverIndex */
server.on("/", HTTP_GET, []() {
server.sendHeader("Connection", "close");
server.send(200, "text/html", loginIndex);
});
server.on("/serverIndex", HTTP_GET, []() {
server.sendHeader("Connection", "close");
server.send(200, "text/html", serverIndex);
});
/*handling uploading firmware file */
server.on("/update", HTTP_POST, []() {
server.sendHeader("Connection", "close");
server.send(200, "text/plain", (Update.hasError()) ? "FAIL" : "OK");
ESP.restart();
}, []() {
HTTPUpload& upload = server.upload();
if (upload.status == UPLOAD_FILE_START) {
Serial.printf("Update: %s\n", upload.filename.c_str());
if (!Update.begin(UPDATE_SIZE_UNKNOWN)) { //start with max available size
Update.printError(Serial);
}
} else if (upload.status == UPLOAD_FILE_WRITE) {
/* flashing firmware to ESP*/
if (Update.write(upload.buf, upload.currentSize) != upload.currentSize) {
Update.printError(Serial);
}
} else if (upload.status == UPLOAD_FILE_END) {
if (Update.end(true)) { //true to set the size to the current progress
Serial.printf("Update Success: %u\nRebooting...\n", upload.totalSize);
} else {
Update.printError(Serial);
}
}
});
server.begin();
}

void loop(){
server.handleClient();
delay(1000);
printLocalTime();
audio.loop();
if(Serial.available()){ // put streamURL in serial monitor
audio.stopSong();
String r=Serial.readString(); r.trim();
if(r.length()>5) audio.connecttohost(r.c_str());
log_i("free heap=%i", ESP.getFreeHeap());
}
if (segundos == 0){
audio.loop();//play again.
}
}

void printLocalTime(){
struct tm timeinfo;
if(!getLocalTime(&timeinfo)){
Serial.println("Failed to obtain time");
return;
}
//Serial.println(&timeinfo, "%A, %B %d %Y %H:%M:%S");

char hh[3];
strftime(hh,3, "%H", &timeinfo);
hora = String(hh).toInt();
Serial.print(hora);Serial.print(":");

char mm[3];
strftime(mm,3, "%M", &timeinfo);
minutos = String(mm).toInt();
Serial.print(minutos);Serial.print(":");

char ss[3];
strftime(ss,3, "%S", &timeinfo);
segundos = String(ss).toInt();
Serial.print(segundos);Serial.print(" ");

char DoM[3];
strftime(DoM,3, "%d", &timeinfo);
diaMes = String(DoM).toInt();
Serial.print(diaMes);Serial.print(" del ");

char mmes[10];
String mes;
strftime(mmes,10, "%B", &timeinfo);
mes = String(mes + mmes);
byteMes = conv_mes_en_numero(mes);
Serial.print(byteMes);Serial.print(" de ");

char aa[5];
strftime(aa,5, "%Y", &timeinfo);
ano = String(aa).toInt();
Serial.print(ano);Serial.print(" ");

char timeWeekDay[10];
String nombre;
strftime(timeWeekDay,10, "%A", &timeinfo);
nombre = String(nombre + timeWeekDay);
Serial.print(nombre);Serial.print(" ");
diaSemana = conv_diaSemana_en_numero(nombre);
Serial.print("DoW: ");Serial.print(diaSemana);
Serial.print(". Se ajustó la hora ");Serial.print("el día ");Serial.print(comprobadorDiaMes);Serial.print(" a las ");Serial.println(comprobadorCambioHora);
if ((diaSemana == 1) && (hora == 8) && (minutos == 0) && (segundos == 0)){interruptor_poner_en_hora = HIGH;}
if (interruptor_poner_en_hora == HIGH){poner_en_hora(ptr_hora, ptr_diaMes);}
}

byte conv_diaSemana_en_numero(String valor){
if (valor == "Monday"){return 1;}
else if (valor == "Tuesday"){return 2;}
else if (valor == "Wednesday"){return 3;}
else if (valor == "Thursday"){return 4;}
else if (valor == "Friday"){return 5;}
else if (valor == "Saturday"){return 6;}
else if (valor == "Sunday"){return 7;}
}

byte conv_mes_en_numero(String valor){
if (valor == "January"){return 1;}
else if (valor == "February"){return 2;}
else if (valor == "March"){return 3;}
else if (valor == "April"){return 4;}
else if (valor == "May"){return 5;}
else if (valor == "June"){return 6;}
else if (valor == "July"){return 7;}
else if (valor == "August"){return 8;}
else if (valor == "September"){return 9;}
else if (valor == "October"){return 10;}
else if (valor == "November"){return 11;}
else if (valor == "December"){return 12;}
}

void poner_en_hora(int *h, int *d){
Serial.println("Bajando la hora exacta...");
if (WiFi.status() == WL_CONNECTED) {
configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);
Serial.println("Hora exacta ajustada.");
comprobadorCambioHora = *h;
comprobadorDiaMes = *d;
} else {
Serial.println("No hay conexión a internet. Mañana se intentará.");
}

interruptor_poner_en_hora = LOW;
}

void conectar_wifi(){// Connect to Wi-Fi
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
for (int i = 0 ; i < 20 ; i++){
if (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(20 - i);Serial.print(".");
} else {
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
Serial.println(WiFi.macAddress());
break;
}
}
}

Who is online

Users browsing this forum: Bing [Bot], kaxx1975 and 46 guests