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

95 lines
2.3 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",
8192, // Stack size (ESP32-audioI2S requires a larger stack size for decoding)
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;
}
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();
// Match WAV or MP3 files
if (strstr(name, ".wav") || strstr(name, ".mp3") || strstr(name, ".WAV") || strstr(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);
}