SimpleSDAudio play while Pushbutton pressed

Hi.

I am using the SimpeSDAudio library to play an audio sample when I press a button. But I want the audio to play continuously only while the button is pressed down.

I have managed to play the whole recording when you press the button once and also to continuously read the pushbutton data, but then it plays the recording from the beginning every time.

The current code below plays the sample until the end when you press the button once. How could I get it to continue reading the pushbutton data and while it reads '1' continuously play the audio and stop when it reads '0' again even if the recording hasn't finished?

#include <SimpleSDAudio.h>

const int buttonPin = 2; 
int buttonState = 0; 

void setup()
{
  Serial.begin(9600);
  pinMode(buttonPin, INPUT);
}


void loop(void) {
 buttonState = digitalRead(buttonPin);
 Serial.println(buttonState);
 
 if (buttonState == HIGH) {
    if (!SdPlay.init(SSDA_MODE_FULLRATE | SSDA_MODE_MONO | SSDA_MODE_AUTOWORKER)) {
      Serial.println(SdPlay.getLastError());
      while(1);
      }
    if(!SdPlay.setFile("MaleNEW.raw")) {
      Serial.println(SdPlay.getLastError());
      while(1);
      }      

    SdPlay.play();
    // deleting this part keeps reading button data:
    while(!SdPlay.isStopped()) {
      ;
      }

    SdPlay.deInit();
  }
  
}[code]

Hi there!

I've never used this library before so forgive me if I say something wrong.

From your code, my interpretation is that if the button is pressed (buttonState==HIGH), the system will check if the audio is initialized and the file is set correctly. If it is, it will then start to play. This loop portion will happen every so many milliseconds so it does appear that the audio file will restart every so many seconds. What you can try to do is add a small nested loop inside your main loop that checks if the button is pushed. Perhaps something like the following:

.....//Your initialization code and such here

SdPlay.Play();

buttonState = digitalRead(buttonPin);
while(buttonState==HIGH)
{
  buttonState = digitalRead(buttonPin);
  if(buttonState == HIGH)
  {
    
  }
  else
  {
    break;
  }
}

This code should keep the main loop from exiting until the button is released, at which point the "deInit() function will be called and the audio should stop.

Let me know if this works!

Yes, this solved the problem.

I changed your 'break' line after 'else' into SdPlay.deInit(); and now it works perfectly.

Thank you so much for this!!