I wrote the file search code, I write only one track value, but it does not work,
even the files are somehow not found, on Sd card their 14
Songs found:8
Songs List:
SYSTEM~1
1.WAV
2.WAV
3.WAV
55.WAV
Play button
SW4=!digitalRead(2);
if (SW4 && !playStop && !playStopProm && !playStopProm2 && millis() - btnTimer > 100) {
recordprom = 0;
playStop = true;
btnTimer = millis();
listSongs(dir);
music.play(musics[0]);
}
Next track button
SW2=!digitalRead(5);
if (SW2 && !next && playStopProm && millis() - btnTimer > 100) {
next = true;
btnTimer = millis();
++counter %= 3;
nexttrack++;
listSongs(dir);
music.play(musics[0]);
}
Card reading
void listSongs(File folder){
nSongs = 0;
while(true){
File entry = folder.openNextFile();
if(!entry){
folder.rewindDirectory();
break;
}else{
nSongs++;
}
entry.close();
}
Serial.print("Songs found:");
Serial.println(nSongs);
songList = new String[nSongs];
Serial.println("Songs List:");
for(int i = 0; i < songList; i++){
File entry = folder.openNextFile();
if (i == nexttrack) {
musics[0] = {entry.name()};
}
songList[i] = entry.name();
entry.close();
Serial.println(songList[i]);
}
}
All the code
/*
This sketch demonstrates recording of standard WAV files that can be played on any device that supports WAVs. The recording
uses a single ended input from any of the analog input pins. Uses AVCC (5V) reference currently.
Requirements:
Class 4 or 6 SD Card
Audio Input Device (Microphone, etc)
Arduino Uno,Nano, Mega, etc.
Steps:
1. Edit pcmConfig.h
a: On Uno or non-mega boards, #define buffSize 128. May need to increase.
b: Uncomment #define ENABLE_RECORDING and #define BLOCK_COUNT 10000UL
2. Usage is as below. See <a href="https://github.com/TMRh20/TMRpcm/wiki/Advanced-Features#wiki-recording-audio" title="https://github.com/TMRh20/TMRpcm/wiki/Advanced-Features#wiki-recording-audio" rel="nofollow">https://github.com/TMRh20/TMRpcm/wiki/Advanced-Features#wiki-recording-a...</a> for
additional informaiton.
Notes: Recording will not work in Multi Mode.
Performance is very dependant on SD write speed, and memory used.
Better performance may be seen using the SdFat library. See included example for usage.
Running the Arduino from a battery or filtered power supply will reduce noise.
*/
#include <SD.h>
#include <SPI.h>
#include <TMRpcm.h>
#include <EEPROM.h>
#define path "/"
String *songList;
File dir;
int nSongs = 0;
//#define ENABLE_DEBUG //Включение вывода отладочной информации через Serial. Только для отладки! Закоментировать эту строку перед заливкой в готовое устройство!
#define SD_ChipSelectPin 10 //
#define MicPin A7 // Аналоговый пин, к которму подключен микрофон
int SW3;
uint32_t btnTimer = 0;
bool record = false;
bool recordprom = false;
char NameRecord[10]; // Имя нового - записываемого файла на SD-карту
int RecordNumber; // Номер записи - храним в EEPROM. в диапазоне от 0 до 32767
byte Recording = 0; // Переменная определяет идет сейчас запись или нет
//-----------------------------------------------
int RecInterval = 5; //! Минимальная продолжительность записи в секундах !
//-----------------------------------------------
unsigned long TimeInterval = 0; // Переменная для вычисления времени
int MaxAnalogPinValue = 1000; // Уровень сигнала на аналоговом входе при котором произойдет старт записи
// Значение подбирается индивидуально! (100 - 1023)
int SaveADC1 = 0;
int SaveADC2 = 0;
unsigned int sample;
unsigned int signalMax = 0;
unsigned int signalMin = 256;
unsigned int peakToPeak = 0;
#define peakToPeakMinLevel 200 // Уровень срабатывания на звук. Значение подбирается индивидуально!
// Максимальное значение - 255
TMRpcm music; // create an object for use in this sketch
///////
int SW1;
int SW2;
int SW4;
bool pause = false;
bool next = false;
bool playStop = false;
bool playStopProm = false;
bool playStopProm2 = false;
char *musics[] = {"/sound/1.WAV", "/sound/2.WAV", "/sound/3.WAV"};
uint8_t counter;
int nexttrack = 1;
///////
void setup() {
#if defined (ENABLE_DEBUG)
Serial.begin(9600);
#endif
pinMode(4, INPUT_PULLUP);
//audio.speakerPin = 11; //5,6,11 or 46 on Mega, 9 on Uno, Nano, etc
pinMode(10,OUTPUT); //Pin pairs: 9,10 Mega: 5-2,6-7,11-12,46-45
if (!SD.begin(SD_ChipSelectPin)) {
return;
}else{
}
analogReference(EXTERNAL);
// The audio library needs to know which CS pin to use for recording
music.CSPin = SD_ChipSelectPin;
RecordNumber = EEPROM.read(0);
RecInterval = RecInterval * 1000;
////////
pause = false;
pinMode(3, INPUT_PULLUP);
pinMode(5, INPUT_PULLUP);
pinMode(2, INPUT_PULLUP);
music.speakerPin = 9;
music.setVolume(4);
//////
dir = SD.open(path);
}
void loop() {
////////////
SW4=!digitalRead(2);
if (SW4 && !playStop && !playStopProm && !playStopProm2 && millis() - btnTimer > 100) {
recordprom = 0;
playStop = true;
btnTimer = millis();
listSongs(dir);
music.play(musics[0]);
}
if (!SW4 && playStop && !playStopProm && !playStopProm2 && millis() - btnTimer > 100)
{
playStopProm = !playStopProm;
btnTimer = millis();
}
if (SW4 && playStop && playStopProm && !playStopProm2 && millis() - btnTimer > 100) {
playStopProm2 = !playStopProm2;
btnTimer = millis();
music.stopPlayback();
recordprom = 0;
}
if (!SW4 && playStop && playStopProm && playStopProm2 && millis() - btnTimer > 100)
{
playStopProm = false;
playStop = false;
playStopProm2 = false;
btnTimer = millis();
}
//Serial.println(musics[0]);
SW1=!digitalRead(3);
if (SW1 && !pause && millis() - btnTimer > 100) {
pause = true;
btnTimer = millis();
music.pause();
}
if (!SW1 && pause && millis() - btnTimer > 100)
{ // если SW1 нажата, то воспроизвести файл "6.wav"
pause = false;
btnTimer = millis();
}
SW2=!digitalRead(5);
if (SW2 && !next && playStopProm && millis() - btnTimer > 100) {
next = true;
btnTimer = millis();
++counter %= 3;
nexttrack++;
listSongs(dir);
music.play(musics[0]);
}
if (!SW2 && next && millis() - btnTimer > 100)
{ // если SW1 нажата, то воспроизвести файл "6.wav"
next = false;
btnTimer = millis();
}
////////////////
SW3=!digitalRead(4);
if (SW3 && !record && millis() - btnTimer > 100) {
playStopProm = true;
playStop = true;
music.stopPlayback();
record = true;
recordprom = !recordprom;
btnTimer = millis();
Serial.println ("push");
Serial.println (recordprom);
}
if (!SW3 && record && millis() - btnTimer > 100)
{ // если SW1 нажата, то воспроизвести файл "6.wav"
record = false;
btnTimer = millis();
}
if (Recording == 0){
int AnR = analogRead(MicPin);
#if defined (ENABLE_DEBUG)
Serial.print("Analog level: ");
Serial.println(AnR);
#endif
if (recordprom == 1) {
#if defined (ENABLE_DEBUG)
Serial.print("Start recording! File: ");
Serial.print(RecordNumber+1);
Serial.println(".wav");
#endif
StartRec();
}
}
if (Recording == 1){
sample = ADCH;
if (sample < 256)
{
if (sample > signalMax)
{
signalMax = sample; // save just the max levels
}
else if (sample < signalMin)
{
signalMin = sample; // save just the min levels
}
}
#if defined (ENABLE_DEBUG)
Serial.print("Max MIC signal: ");
Serial.println(signalMax);
#endif
if (recordprom == 0) {
analogRead(MicPin);
StopRec();
#if defined (ENABLE_DEBUG)
Serial.println("Recording stopped");
#endif
}
}
}
void listSongs(File folder){
nSongs = 0;
while(true){
File entry = folder.openNextFile();
if(!entry){
folder.rewindDirectory();
break;
}else{
nSongs++;
}
entry.close();
}
Serial.print("Songs found:");
Serial.println(nSongs);
songList = new String[nSongs];
Serial.println("Songs List:");
for(int i = 0; i < songList; i++){
File entry = folder.openNextFile();
if (i == nexttrack) {
musics[0] = {entry.name()};
}
songList[i] = entry.name();
entry.close();
Serial.println(songList[i]);
}
}
void StartRec() { // begin recording process
SaveADC1 = ADCSRA;
SaveADC2 = ADCSRB;
Recording = 1;
RecordNumber++;
if (RecordNumber > 32766)RecordNumber = 0; // небольшое огриничение в номерации файлов
EEPROM.write(0, RecordNumber); // Сохранение в EEPROM номера последнего аудиофайла
TimeInterval = millis(); // Запоминаем millis для отсчета времени записи
sprintf(NameRecord,"%d.wav", RecordNumber); // создаем название файла из номера и расширения ".wav"
music.startRecording(NameRecord, 16000, MicPin, 0);// Старт записи
}
void StopRec() { // stop recording process, close file
music.stopRecording(NameRecord);// Стоп записи
Recording = 0;
ADCSRA = SaveADC1;
ADCSRB = SaveADC2;
}