Read the list of audio files from the SD flash drive, followed by its playback

Hello, I cannot correctly read all audio files from a flash drive into an array for playback through the TMRpcm.h library, maybe someone can help

#include <SD.h>
#include <SPI.h>
#define SD_ChipSelectPin 10
#define path "/"
#include <TMRpcm.h>
TMRpcm music;
int SW1;
int SW2; 
int SW4;
uint32_t btnTimer = 0;
bool pause = false; 
bool next = false;
bool playStop = false;
bool playStopProm = true;
char *musics[] = {};
String *songList;
File dir;
int truesound;
int nSongs = 0;
int nFile = 0;
uint8_t counter;


void setup() {
  Serial.begin(9600);
  while(!Serial){
  }
  pause = false;
  pinMode(3, INPUT_PULLUP);
  pinMode(5, INPUT_PULLUP);
  pinMode(2, INPUT_PULLUP);
  music.speakerPin = 9;
  music.setVolume(4);
 if (!SD.begin(SD_ChipSelectPin)) // проверить, есть ли карта, и может ли она быть инициализирована:
  {  
    return;                        // если нет, то ничего не делать
  }
 dir = SD.open(path);
  listSongs(dir);
}
void listSongs(File folder){
  nSongs = 0;
  nFile = 0;
  while(true){
    File entry = folder.openNextFile();
    int8_t len = strlen(entry.name());
    if(!entry){
      folder.rewindDirectory();
      break;
    }else{
    nFile++;
    }
    if (strstr(strlwr(entry.name() + (len - 4)), ".wav")){
      nSongs++;
    } 
    entry.close();
  }

  Serial.print("Songs found:");
  Serial.println(nSongs);

  songList = new String[nSongs];
  Serial.println("Songs List:");

  truesound = 0;
  for(int i = 0; i < nFile; i++){
    File entry = folder.openNextFile();
    int8_t len = strlen(entry.name());
    if (strstr(strlwr(entry.name() + (len - 4)), ".wav")){
    songList[truesound] = entry.name();
    musics[truesound] = entry.name();
   truesound++;
    }
     entry.close();
    // Serial.println(songList[]);
     Serial.println(musics[truesound]);
  }

}

void loop() {

SW4=!digitalRead(2);
  if (SW4 && !playStop && millis() - btnTimer > 100) {
    playStop = true;
    playStopProm = !playStopProm;
    btnTimer = millis();
    Serial.println ("push");
    Serial.println (playStopProm);
   
  }
if (!SW4 && playStop && millis() - btnTimer > 100)
  { 
  playStop = false;
  btnTimer = millis();
  } 

  //Serial.println(musics[0]);
if (playStopProm == 1) {
    music.play(musics[counter]);
     ++counter %= 3;
 }

  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 && millis() - btnTimer > 100) {
    next = true;
    btnTimer = millis();
     music.play(musics[counter]);
    ++counter %= 3;
  }
if (!SW2 && next && millis() - btnTimer > 100)
  { // если SW1 нажата, то воспроизвести файл "6.wav"
  next = false;
  btnTimer = millis();
  } 
}


This creates an array of pointers with zero elements. So e.g. musics[0] assigning a value to it will probably result in a crash.

I specified the size but it didn't help

Which size did you use; is it enough to hold all musics?

This might be another problem

void listSongs(File folder) {
  nSongs = 0;
  nFile = 0;
  while (true) {
    File entry = folder.openNextFile();
    int8_t len = strlen(entry.name());

If entry equals null (!entry), your program can crash on the last line; you have a check after that so that last line should move down.

What is the number of nSongs (10, 100, 1000, ...)? You might be running out of memory if there are too many songs. I do not know which Arduino you're using but you can check the available RAM (for Arduino boards see https://docs.arduino.cc/learn/programming/memory-guide/#sram-memory-measurement, I do not know about ESP boards).

I compiled for an Uno and got 953 bytes free RAM; 100 song entries would add at least 600 bytes (just for the array of String objects, not even the names themselves) and will get you in the danger zone if you're using a 328P based processor.

This is a little demo of the memory usage for 20 songs in songList with short names

String *songList;
uint16_t nSongs = 20;

void setup()
{
  Serial.begin(115200);
  Serial.print(F("Start"));
  display_freeram();

  songList = new String[nSongs];
  Serial.print(F("After new"));
  display_freeram();

  for (uint16_t cnt = 0; cnt < nSongs; cnt++)
  {
    songList[cnt] = String(cnt);
  }
  Serial.print(F("After assigning"));
  display_freeram();
}

void loop()
{
}

void display_freeram() {
  Serial.print(F("- SRAM left: "));
  Serial.println(freeRam());
}

int freeRam() {
  extern int __heap_start, *__brkval;
  int v;
  return (int)&v - (__brkval == 0
                    ? (int)&__heap_start : (int) __brkval);
}

IDE memory report (for a classic Nano)


Global variables use 200 bytes (9%) of dynamic memory, leaving 1848 bytes for local variables. Maximum is 2048 bytes.

The output (for a classic Nano)

09:13:52.800 -> Start- SRAM left: 1811
09:13:52.800 -> After new- SRAM left: 1607
09:13:52.800 -> After assigning- SRAM left: 1578

up to 500 records, I use Arduino pro micro 16 MHz. processor 32u4. name from 1 to 500

Pro micro has 2.5KB of dynamic/RAM.

If the file names are only 8 characters long, then for 500 files a minimum of 4KB would be needed.

Do you need to store all the file names in RAM?

not necessarily, the essence of the task is to record audio files using a microphone and then play it back

like this project

Have you seen something similar achieved with a Pro Micro?

no, I saw only separate sound reproduction and recording with the help of a micro

i have done almost everything except opening the recorded files

Here is the code that I wrote, but here the names that I specified are played, but I need the name to be determined from the flash drive themselves and switched for listening

/*
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 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"};
File dir;
int nSongs = 0;
uint8_t counter;

///////
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);
//////
}


void loop() {
////////////
SW4=!digitalRead(2);
  if (SW4 && !playStop && !playStopProm && !playStopProm2 && millis() - btnTimer > 100) {
    recordprom = 0;
    playStop = true;
    btnTimer = millis();
    music.play(musics[counter]);
  }
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;
     music.play(musics[counter]);
    
  }
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 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;
}

The SD card library has an example sketch which lists the files in a directory/folder on the card. Take a look at that to see how that works.

I can display the list of files that are on the card, but I can't figure out how to play them, because the list of files is written in a String, and music.play(musics[counter]); I still can't figure out what the file type should be

music.play() takes either a char* or a __FlashStringHelper*, so the file name is stored in either a char array, or a char array in PROGMEM.

Do not try to store the file names, just list the names as you read them from the SD card. When you want to play a song, read through the file names on the SD card again until you reach the one that corresponds to the value in counter, then play that file. If you want the option of entering a filename as text, then compares the files names as they are read from the SD card until you find a match.

could you show how to do it correctly, or maybe have some example?

Are you recording to an SD card or a flash drive, as I thought from post #1?

Also, you said “like this project…”. How closely similar to that telephone project? If very different, could you describe yours in more detail? In particular what exactly is it not doing that you expect?

recording on the sd card, it should be a very similar project, now all that remains is to make it so that when you press a button, pre-recorded audio from the recorder is played, another button switches them, I configured the buttons, the problem is only with opening files because the names and their number are generated after recording from a dictaphone.

I looked quickly through the (rather complex!) guestbook sketch by the project developer, Alistair. Did you notice that there were some statements that are apparently exclusive to the Teensy? IOW not available on other Arduino boards, such as your Pro Mini.

I’m assuming that you carefully viewed the 67 minute video?

I didn't watch the video in its entirety, the task was to make it as simple as possible and with inexpensive elements

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;
}