Playing a wav sample from an SD card when a button is pressed

I've been working recently on a project which is kinda the same.

  • there is no need to create two TMRPCM-Objects. You only need one "TMRpcm tmrpcm".
  • DOn't comment out this line: "tmrpcm.speakerPin = 11". You need a speaker. You can't tell tmrpcm with "pinMode(11, INPUT)" to use your speaker. Also: if it would work with "pinMode" it should be set as an "OUTPUT" since a speaker commonly is a output-device.
  • What kind of speaker do you use?
  • How did you connect your speaker to the arduino? (As for my project I used a JBL-Box with a aux-to-aux cable. You have many different options so it would be nice to know how you connected your speaker)

Now some more thing you might want to try out:
Use a 1k ohm Resistor between your datapin and button to the ground. With that the remaining electrons are cleared from the button and you can get a better "HIGH-LOW"-Status.

Use some variables to check the status of an button. Then use the if-statement to check if a button is pressed.

You can try this:

#include <SD.h> //Include the library.
#include <TMRpcm.h> //Include the library.

TMRpcm tmrpcm; //Creating a player object.


const int chipSelect = 4;
const int buttonState1 = 0;
const int buttonState2 = 0;

void setup()
{

  pinMode(9,INPUT);
  pinMode(10,INPUT);
  //pinMode(11,INPUT);
  pinMode(12,INPUT);

  tmrpcm.speakerPin = 11; //The speaker is connected to 11 Pin. You can use any PWM Pin.
  Serial.begin(9600); //Initializing serial port. Speed 9600.
  if(!SD.begin(chipSelect)) //If the card is available.
  {
    Serial.println("SD fail"); //Write in the serial port "SD fail".
    return; //Return.
  }
  Serial.println("SD working");

  
}

void loop()
{
buttonState1 = digitalRead(9);
buttonState2 = digitalRead(10);

if(buttonState1 == HIGH){  
  tmrpcm.play("transMono1.wav"); //Play music file 
   Serial.println("button 1 pressed");
  }
  else{
    tmrpcm.pause();
  }

  if(buttonState2 == HIGH){  
  tmrpcm.play("transMono3.wav"); //Play music file 
   Serial.println("button 2 pressed");
  }
  else{
    tmrpcm.pause
  }
}

I don't guarantee you that this is working 100% correctly since I can't test it out right now.