写一个基于Arduino的ESP32播放MP3文件的代码
时间: 2023-08-31 18:26:51 浏览: 235
### 回答1:
以下是基于Arduino的ESP32播放MP3文件的示例代码:
```C++
#include <WiFi.h>
#include <WiFiClient.h>
#include <WebServer.h>
#include <ESPmDNS.h>
#include <Update.h>
#include <ESPAsyncWebServer.h>
#include <SD.h>
#include <driver/i2s.h>
#include <esp_task_wdt.h>
#include <AudioFileSourceSPIFFS.h>
#include <AudioGeneratorMP3.h>
#include <AudioOutputI2S.h>
// Replace with your network credentials
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
WebServer server(80);
// Pin definitions for ESP32 with I2S
#define I2S_DOUT 25
#define I2S_BCLK 26
#define I2S_LRC 22
// Audio library objects
AudioGeneratorMP3 *mp3;
AudioFileSourceSPIFFS *file;
AudioOutputI2S *out;
void playMP3(String filename) {
if (mp3 != nullptr) {
mp3->stop();
delete mp3;
mp3 = nullptr;
}
if (file != nullptr) {
delete file;
file = nullptr;
}
file = new AudioFileSourceSPIFFS(filename.c_str());
mp3 = new AudioGeneratorMP3();
out = new AudioOutputI2S();
out->SetPinout(I2S_BCLK, I2S_LRC, I2S_DOUT);
mp3->begin(file, out);
}
void handleRoot() {
String html = "<html><body>";
html += "<h1>ESP32 MP3 Player</h1>";
html += "<p><a href=\"/play?file=hello.mp3\">Play Hello</a></p>";
html += "<p><a href=\"/play?file=world.mp3\">Play World</a></p>";
html += "</body></html>";
server.send(200, "text/html", html);
}
void handlePlay() {
String filename = server.arg("file");
if (filename != "") {
playMP3("/" + filename);
server.send(200, "text/plain", "Playing " + filename);
} else {
server.send(400, "text/plain", "Bad Request");
}
}
void setup() {
Serial.begin(115200);
// Connect to Wi-Fi network
WiFi.begin(ssid, password);
Serial.println("");
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
// Start the SD card
if (!SD.begin()) {
Serial.println("Card Mount Failed");
return;
}
Serial.println("SD card mounted");
// Initialize I2S
i2s_config_t i2sConfig = {
.mode = (i2s_mode_t)(I2S_MODE_MASTER | I2S_MODE_TX),
.sample_rate = 44100,
.bits_per_sample = I2S_BITS_PER_SAMPLE_16BIT,
.channel_format = I2S_CHANNEL_FMT_RIGHT_LEFT,
.communication_format = (i2s_comm_format_t)(I2S_COMM_FORMAT_I2S | I2S_COMM_FORMAT_I2S_MSB),
.intr_alloc_flags = ESP_INTR_FLAG_LEVEL1,
.dma_buf_count = 8,
.dma_buf_len = 64
};
i2s_pin_config_t pinConfig = {
.bck_io_num = I2S_BCLK,
.ws_io_num = I2S_LRC,
.data_out_num = I2S_DOUT,
.data_in_num = I2S_PIN_NO_CHANGE
};
i2s_driver_install(I2S_NUM_0, &i2sConfig, 0, NULL);
i2s_set_pin(I2S_NUM_0, &pinConfig);
// Start the web server
server.on("/", handleRoot);
server.on("/play", handlePlay);
server.begin();
Serial.println("Web server started");
}
void loop() {
server.handleClient();
if (mp3 != nullptr && !mp3->isRunning()) {
delete mp3;
mp3 = nullptr;
delete file;
file = nullptr;
out->stop();
delete out;
out = nullptr;
}
delay(10);
}
```
这个示例代码假设你已经连接到了Wi-Fi,并且已经插入了一个带有MP3文件的SD卡。当你访问`http://<ESP32_IP_ADDRESS>/play?file=<FILENAME>`时,它会播放指定的MP3文件。你可以通过修改`ssid`和`password`变量来更改Wi-Fi网络的凭据。
请注意,该代码是基于I2S的,因此请确保你正确连接了I2S引脚。如果你打算使用其他音频输出,你需要相应地修改代码。
### 回答2:
下面是一个基于Arduino的ESP32播放MP3文件的简单代码示例:
```c++
#include <WiFi.h>
#include <ESPAsyncWebServer.h>
#include <ESPAsyncWiFiManager.h>
#include <DFMiniMp3.h>
#define RX_PIN 16
#define TX_PIN 17
#define BAUD_RATE 9600
DFMiniMp3<HardwareSerial, mp3_notify> mp3(RX_PIN, TX_PIN);
void mp3_notify(uint8_t type, uint16_t value)
{
switch (type) {
case TimeOut:
if (value == 0xFFFF) {
Serial.println(F("Time Out!"));
} else {
Serial.print(F("File index not found: "));
Serial.println(value);
}
break;
case WrongStack:
Serial.println(F("Stack Wrong!"));
break;
case DFPlayerCardInserted:
Serial.println(F("Card Inserted!"));
break;
case DFPlayerCardRemoved:
Serial.println(F("Card Removed!"));
break;
case DFPlayerCardOnline:
Serial.println(F("Card Online!"));
break;
case DFPlayerPlayFinished:
Serial.print(F("Finished playing: "));
Serial.println(value);
break;
case DFPlayerError:
Serial.print(F("DFPlayerError: "));
switch (value) {
case Busy:
Serial.println(F("Card not found"));
break;
case Sleeping:
Serial.println(F("Sleeping"));
break;
case SerialWrongStack:
Serial.println(F("Get Wrong Stack"));
break;
case CheckSumNotMatch:
Serial.println(F("Check Sum Not Match"));
break;
case FileIndexOut:
Serial.println(F("File Index Out of Bound"));
break;
case FileMismatch:
Serial.println(F("Cannot Find File"));
break;
case Advertise:
Serial.println(F("In Advertise"));
break;
default:
break;
}
break;
default:
break;
}
}
void setup()
{
Serial.begin(BAUD_RATE);
mp3.begin();
mp3.volume(10); //设置声音大小,0-30
Serial.println("\nWiFi连接...");
AsyncWiFiManager wifiManager(&server);
wifiManager.autoConnect();
Serial.println("WiFi已连接");
}
void loop()
{
// 待机状态
if (mp3.get_state() == Standby) {
mp3.sleep(); // 进入睡眠模式以减少功耗
}
// 播放状态
if (mp3.get_state() == Playing) {
// 执行其他任务
}
// 等待播放完毕
if (mp3.get_state() == Finished) {
mp3.play(); // 继续播放下一首
}
}
```
以上代码需要使用DFPlayer Mini MP3 Player库,你可以通过Arduino库管理器安装该库。
此代码使用WiFiManager库来实现WiFi连接,你需要先安装WiFiManager库,然后在`#include`语句之间添加ESPAsyncWebServer库的头文件。
注意,此示例仅仅演示了如何播放MP3文件,你可以根据自己的需求进行修改并适配不同的ESP32开发板。
阅读全文