Files
sunflower-picture-app/sound_picture_app/Audio_Player.cpp

103 lines
2.6 KiB
C++

#include "Audio_Player.h"
#include "Audio.h"
Audio audio;
TaskHandle_t audioTaskHandle = NULL;
volatile bool isAudioTaskRunning = false;
uint8_t currentVolume = 12; // 0 to 21 range
uint16_t Audio_Count = 0;
char Audio_Names[100][100];
// FreeRTOS background task on Core 0 to run ESP32-audioI2S decode loop
void audioLoopTask(void* parameter) {
isAudioTaskRunning = true;
while (isAudioTaskRunning) {
audio.loop();
vTaskDelay(pdMS_TO_TICKS(1)); // Yield to let other RTOS tasks run
}
audioTaskHandle = NULL;
vTaskDelete(NULL);
}
void initAudioPlayer() {
audio.setPinout(I2S_BCLK, I2S_LRCK, I2S_DIN);
audio.setVolume(currentVolume);
// Start the background loop task on Core 0
if (audioTaskHandle == NULL) {
xTaskCreatePinnedToCore(
audioLoopTask,
"audioLoopTask",
16384, // Increased from 8192 — ESP32-audioI2S MP3 decode needs ~12-16KB stack
NULL,
5, // Priority
&audioTaskHandle,
0 // Core 0
);
}
}
void playAudio(const char* filePath) {
printf("AudioPlayer: Connecting to FS for file: %s\r\n", filePath);
audio.connecttoFS(SD_MMC, filePath);
}
void stopAudio() {
audio.stopSong();
}
void pauseResumeAudio() {
audio.pauseResume();
}
bool isAudioPlaying() {
return audio.isRunning();
}
void setPlayerVolume(uint8_t volume) {
if (volume > 21) volume = 21;
currentVolume = volume;
audio.setVolume(currentVolume);
printf("AudioPlayer: Volume set to %d / 21\r\n", currentVolume);
}
uint8_t getPlayerVolume() {
return currentVolume;
}
// Case-insensitive check if filename ends with a given extension
static bool hasExtension(const char* name, const char* ext) {
size_t nLen = strlen(name);
size_t eLen = strlen(ext);
if (nLen < eLen) return false;
return strcasecmp(name + nLen - eLen, ext) == 0;
}
void Search_Audio(const char* directory) {
File Path = SD_MMC.open(directory);
if (!Path) {
printf("Path: <%s> does not exist\r\n", directory);
Audio_Count = 0;
return;
}
uint16_t fileCount = 0;
File file = Path.openNextFile();
while (file && fileCount < 100) {
if (!file.isDirectory()) {
const char* name = file.name();
// Case-insensitive extension match to handle FAT32 uppercase names
if (hasExtension(name, ".wav") || hasExtension(name, ".mp3")) {
strncpy(Audio_Names[fileCount], name, sizeof(Audio_Names[fileCount]) - 1);
Audio_Names[fileCount][sizeof(Audio_Names[fileCount]) - 1] = '\0';
fileCount++;
}
}
file = Path.openNextFile();
}
Path.close();
Audio_Count = fileCount;
printf("Found %d audio files (.mp3/.wav)\r\n", Audio_Count);
}