Skip to content

Commit ddc5029

Browse files
authored
add playFile() blocking method for audio playback (#2048)
summary: adds a new `playFile(const char *filePath)` method to the `AudioPlayer` class that provides a simple blocking way to play a complete audio file from start to finish. - new method: `bool playFile(const char *filePath)` in the public section of `AudioPlayer` class - functionality: - sets the audio file path using existing `setPath()` method - starts playback with `play()` - blocks execution until the entire file finishes playing - automatically stops when no more audio data is available - returns `true` on success, `false` if file cannot be opened use case: i used this library for an ESP32 project at school and needed a blocking method to do nothing BUT play a specific audio file before continuing the program, so i made my own and thought other people might need it! example usage: ```cpp AudioPlayer player(source, output, decoder); ... setup() { player.begin(); } ... loop() { // play a complete file (blocking) if (player.playFile("/song1.mp3")) { // file plays successfully } else { // file not found or other error occurred } doSomething(); } ``` this addition shouldn't affect any existing functionality!
1 parent 1637404 commit ddc5029

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

src/AudioTools/CoreAudio/AudioPlayer.h

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -252,6 +252,32 @@ class AudioPlayer : public AudioInfoSupport, public VolumeSupport {
252252
setActive(true);
253253
}
254254

255+
/// plays a complete audio file from start to finish (blocking call)
256+
/// @param filePath path to the audio file to play
257+
/// @return true if file was found and played successfully, false otherwise
258+
bool playFile(const char *filePath) {
259+
TRACED();
260+
if (!setPath(filePath)) {
261+
LOGW("Could not open file: %s", filePath);
262+
return false;
263+
}
264+
265+
LOGI("Playing %s", filePath);
266+
play();
267+
268+
while (isActive()) {
269+
size_t bytes_copied = copy();
270+
// if no bytes were copied, the file may have ended
271+
if (bytes_copied == 0) {
272+
stop();
273+
break;
274+
}
275+
}
276+
277+
LOGI("%s has finished playing", filePath);
278+
return true;
279+
}
280+
255281
/// halts the playing: same as setActive(false)
256282
void stop() {
257283
TRACED();

0 commit comments

Comments
 (0)