I'm trying to repeatedly play an audio file on the Sony Spresense. I have tested the example sketches provided by Sony and they work fine for playing an audio file. But if I want to replay the file, I get errors. Unfortunately, all sketches only play their file once...
To keep it simple, I have shrunk the source code.
#include <Audio.h>
#include <SDHCI.h>
static void audioErrorCallback(const ErrorAttentionParam *atprm);
bool initializeSound();
SDClass theSD;
AudioClass *theAudio;
File soundFile;
bool soundFinished;
void setup() {
Serial.begin(115200);
while (!Serial);
initializeSound();
soundFinished = true;
}
void loop() {
if (!soundFinished) {
int err = theAudio->writeFrames(AudioClass::Player0, soundFile);
if (err == AUDIOLIB_ECODE_FILEEND) {
soundFinished = true;
stopPlay();
}
} else {
Serial.println("Sleep");
delay(3000);
soundFinished = false;
startPlay();
}
usleep(40000);
}
static void audioErrorCallback(const ErrorAttentionParam *atprm) {
if (atprm->error_code >= AS_ATTENTION_CODE_WARNING)
{
Serial.println("Error!");
}
}
bool initializeSound() {
theAudio = AudioClass::getInstance();
theAudio->begin(audioErrorCallback);
theAudio->setRenderingClockMode(AS_CLKMODE_NORMAL);
theAudio->setPlayerMode(AS_SETPLAYER_OUTPUTDEVICE_SPHP, AS_SP_DRV_MODE_LINEOUT);
theAudio->initPlayer(AudioClass::Player0, AS_CODECTYPE_MP3, "/mnt/sd0/BIN", AS_SAMPLINGRATE_AUTO, AS_CHANNEL_STEREO);
soundFile = theSD.open("audioFile.mp3");
theAudio->setVolume(-160);
return true;
}
void startPlay() {
theAudio->writeFrames(AudioClass::Player0, soundFile);
theAudio->startPlayer(AudioClass::Player0);
}
void stopPlay() {
theAudio->stopPlayer(AudioClass::Player0);
// soundFile.close();
}
The audio file is played without problems for the first time. Afterwards, I receive the following error, always:
Attention: module[5] attention id[2]/code[6] (objects/media_player/player_input_device_handler.cpp L220)
Error!
ERROR: Command (0x22) fails. Result code(0xf1) Module id(0x5) Error code(0x2f) Error subcode(0x0)
ERROR: Command (0x23) fails. Result code(0xf1) Module id(0x5) Error code(0x1)
What's missing? Any ideas?
I had a similar issue, and I was able to fix it by closing the File at the end, and creating a new File at the the start of the loop() instead of in the setup() function.