Hello,
I would like to play an audio file (.WAV) from the SD card while there will a push button pressed and the audio will the played until the button is released. Means the audio will stop while the button is not pressed. I have wrote a simple code using TMRpcm library but the audio is not playing. But if I add a delay function then if I pressed the button the audio is playing as per the ms mentioned in the delay function. I am shearing my codes. Please help me to solve the issue.
Code without delay : Not playing the audio
#include <SD.h>
#include <TMRpcm.h>
#include <SPI.h>
#define SD_ChipSelectPin 53
int switch1 = 8;
TMRpcm audio;
void setup(){
-
audio.speakerPin = 5; // 5, 6, 11 or 46 on Mega, 9 on Uno, Nano, etc*
pinMode (switch1, OUTPUT); -
Serial.begin(9600);*
-
if (!SD.begin(SD_ChipSelectPin)) {*
-
Serial.println("SD fail"); *
-
return;*
-
}*
-
Serial.println("SD Pass");*
-
audio.play("fivesec.wav");*
-
delay(100); // Play an Audio at the startup*
}
*void loop(){ * -
if (digitalRead(switch1) == HIGH)*
-
{*
-
Serial.println("Switch Pressed");*
-
Serial.println("SQUARE.wav");*
-
audio.play("SQUARE.wav",0);*
-
}*
-
else*
-
audio.stopPlayback();*
}
Code with delay : playing the audio file with 100 ms delay
#include <SD.h>
#include <TMRpcm.h>
#include <SPI.h>
#define SD_ChipSelectPin 53
int switch1 = 8;
TMRpcm audio;
void setup(){
-
audio.speakerPin = 5; // 5, 6, 11 or 46 on Mega, 9 on Uno, Nano, etc*
pinMode (switch1, OUTPUT); -
Serial.begin(9600);*
-
if (!SD.begin(SD_ChipSelectPin)) {*
-
Serial.println("SD fail"); *
-
return;*
-
}*
-
Serial.println("SD Pass");*
-
audio.play("fivesec.wav");*
-
delay(100); // Play an Audio at the startup*
}
*void loop(){ * -
if (digitalRead(switch1) == HIGH)*
-
{*
-
Serial.println("Switch Pressed");*
-
Serial.println("SQUARE.wav");*
-
audio.play("SQUARE.wav",0);*
-
delay(100); // Plays the audio file SQUARE.wav for 100 ms*
-
}*
-
else*
-
audio.stopPlayback();*
}