/*
* Simple demo of playing audio from SD card, without use of the
* AudioPlaySdWav class (which accesses the card under interrupt).
*/
#include <Audio.h>
// GUItool: begin automatically generated code
AudioPlayQueue queue; //xy=313,217
AudioOutputI2S i2sOut; //xy=492,218
AudioConnection patchCord1(queue, 0, i2sOut, 0);
AudioConnection patchCord2(queue, 0, i2sOut, 1);
AudioControlSGTL5000 audioShield; //xy=479,279
// GUItool: end automatically generated code
#define LOW_WATER 10 // re-load queue when we only have this many blocks in it
#define LOAD_SIZE 20 // load this many blocks to queue
//=============================================================
bool reload(File& f, AudioPlayQueue& q)
{
bool result = true;
size_t sampleCount = LOAD_SIZE * AUDIO_BLOCK_SAMPLES;
int16_t buffer[sampleCount]; // enough space for a full reload
size_t got = f.read(buffer, sampleCount * sizeof *buffer); // get some data: got is byte count...
got /= sizeof *buffer; // ...and now sample count
for (int i=0; i < LOAD_SIZE && got > 0; i++)
{
if (got >= AUDIO_BLOCK_SAMPLES) // we have a full block...
got -= AUDIO_BLOCK_SAMPLES;
else // not a full block: file must be exhausted
{
result = false; // say playback's finished
memset(buffer + i*AUDIO_BLOCK_SAMPLES + got,0,(AUDIO_BLOCK_SAMPLES - got)*sizeof *buffer); // silence the end and...
got = 0;
}
q.play(buffer + i*AUDIO_BLOCK_SAMPLES, AUDIO_BLOCK_SAMPLES); // ...transmit to audio
}
return result;
}
//=============================================================
void setup()
{
AudioMemory(50); // plenty of space for audio buffering
audioShield.enable();
audioShield.volume(0.1);
SD.begin(BUILTIN_SDCARD); // change to suit your hardware
}
//=============================================================
enum {starting, playing, waiting} state;
uint32_t waitStarted;
File audio;
const char* fname = "sweep100-1k.wav"; // change this to a file you have!
void loop()
{
switch (state)
{
case starting:
audio = SD.open(fname);
state = playing;
break;
case playing:
[COLOR="#FF0000"] if (AudioMemoryUsage() < LOW_WATER) // not ideal[/COLOR]
{
bool fileOK = reload(audio,queue);
if (!fileOK)
{
audio.close();
waitStarted = millis();
state = waiting;
}
}
break;
case waiting:
if (millis() - waitStarted > 1000)
state = starting;
break;
}
}