#include <FS.h>
#include <SD.h>
const int SD_CS = 4;
const int AUDIO_PIN = A0;
const int SAMPLE_RATE = 8000; // Samples per second
const int BIT_DEPTH = 16;
const int RECORD_DURATION = 5; // Record length in seconds
char filename[] = "audio.wav";
String mime_type = "audio/x-wav";
void recordAudio(const char* filename) {
// Check if the file exists and delete it
if (SD.exists(filename)) {
if (SD.remove(filename)) {
Serial.println("Previous audio file deleted.");
} else {
Serial.println("Failed to delete previous audio file.");
return; // Don't proceed if deletion fails
}
}
File audioFile = SD.open(filename, FILE_WRITE);
if (!audioFile) {
Serial.println("Failed to create audio file.");
return;
}
Serial.println("Start recording");
// Write WAV header
writeWavHeader(audioFile, SAMPLE_RATE, BIT_DEPTH, 1); // 1 channel (mono)
int numSamples = SAMPLE_RATE * RECORD_DURATION;
for (int i = 0; i < numSamples; i++) {
int rawValue = analogRead(AUDIO_PIN);
int16_t sample = map(rawValue, 0, 1023, -32768, 32767); // Convert to 16-bit
audioFile.write((uint8_t*)&sample, 2); // Write 2 bytes (16 bits)
delayMicroseconds(1000000 / SAMPLE_RATE); // Delay to maintain sample rate
}
audioFile.close();
Serial.print("Audio recorded to ");
Serial.println(filename);
}
void writeWavHeader(File& file, int sampleRate, int bitDepth, int channels) {
uint32_t byteRate = sampleRate * channels * bitDepth / 8;
uint16_t blockAlign = channels * bitDepth / 8;
file.write("RIFF");
uint32_t fileSize = 36 + RECORD_DURATION * byteRate;
file.write((uint8_t*)&fileSize, 4); // File size - 8
file.write("WAVE");
file.write("fmt ");
uint32_t subchunk1Size = 16;
file.write((uint8_t*)&subchunk1Size, 4); // Subchunk1Size
uint16_t audioFormat = 1;
file.write((uint8_t*)&audioFormat, 2); // AudioFormat (1 = PCM)
file.write((uint8_t*)&channels, 2);
file.write((uint8_t*)&sampleRate, 4);
file.write((uint8_t*)&byteRate, 4);
file.write((uint8_t*)&blockAlign, 2);
file.write((uint8_t*)&bitDepth, 2);
file.write("data");
uint32_t subchunk2Size = RECORD_DURATION * byteRate;
file.write((uint8_t*)&subchunk2Size, 4); // Subchunk2Size
}
void setup() {
Serial.begin(115200);
while (!Serial) ;
}
void loop() {
recordAudio("audio.wav");
delay(10000);
}
}
Created October 5, 2017
Comments
Please log in or sign up to comment.