Minimal Repro below. Note that a "test.wav" file is required on the SD card. The issue seems to stem from reading and writing to the SD card at the same time. In my case the card is a SanDisk Extreme A2.
Any ideas on how to fix this and prevent teensy from crashing?
Any ideas on how to fix this and prevent teensy from crashing?
C++:
#include <Audio.h>
#include <SD.h>
#include <SPI.h>
// Audio Recording
const int BUFFER_SIZE = 8192; // Increased buffer size
byte buffer1[BUFFER_SIZE];
byte buffer2[BUFFER_SIZE];
byte* activeBuffer = buffer1;
byte* writeBuffer = buffer2;
int bufferIndex = 0;
bool shouldSwap = false;
AudioInputI2S audioInput;
AudioRecordQueue queue;
AudioConnection patchCord1(audioInput, 0, queue, 0);
// Audio Playback
AudioPlaySdWav playWav;
AudioOutputI2S audioOutput;
AudioConnection patchCord2(playWav, 0, audioOutput, 0);
AudioConnection patchCord3(playWav, 1, audioOutput, 1);
AudioConnection patchCord4(audioInput, 0, audioOutput, 0);
AudioControlSGTL5000 audioShield;
void setup() {
Serial.begin(9600);
while (!Serial) ; // Wait for Serial to be ready
Serial.println("booted up");
AudioMemory(120);
Serial.println("Audio memory set");
audioShield.enable();
audioShield.inputSelect(AUDIO_INPUT_MIC);
audioShield.volume(0.3);
if (!SD.begin(BUILTIN_SDCARD)) {
Serial.println("SD Card initialization failed!");
return;
}
Serial.println("SD Card initialized");
playWav.play("test.wav");
Serial.println("Playback started");
delay(2000); // a couple seconds to confirm audio playback is working
queue.begin(); // Start the recording queue
Serial.println("Recording queue begun");
}
void loop() {
// Recording logic
if (queue.available() > 0) {
// Fetch a block of audio data
memcpy(activeBuffer + bufferIndex, queue.readBuffer(), 256);
bufferIndex += 256;
if (bufferIndex >= BUFFER_SIZE) {
bufferIndex = 0; // Reset the buffer index
shouldSwap = true;
}
queue.freeBuffer(); // Release the buffer back to the queue
// Swap buffers and write to SD card in a non-blocking manner
if (shouldSwap) {
byte* temp = activeBuffer;
activeBuffer = writeBuffer;
writeBuffer = temp;
shouldSwap = false;
// Write the buffer to the SD card in a new function
writeBufferToSD(writeBuffer);
}
}
}
void writeBufferToSD(byte* buffer) {
// Non-blocking write to SD card
File dataFile = SD.open("recording.raw", FILE_WRITE);
if (dataFile) {
dataFile.write(buffer, BUFFER_SIZE);
dataFile.close();
}
}
Last edited: