Arduino due wav audio on key-press

i'm building a simple piano using a due. what i have so far is an sd shield with a wav file, and a button that is supposed to play the file every time it is pressed. whenever i reset the board, the first press works great, but any next one comes out buffered and messed up. i believe it has something to do with the buffer not resetting after playing the file, but i don't understand how to do it.

#include <SD.h>
#include <SPI.h>
#include <Audio.h>

struct Key
{
  int keyPin;
  int ledPin;
  File noteAudio;

};
Key key;
bool key_released;
int volume;
const int S=1024; // Number of samples to read in block
short buffer[S];


void setup() {
  // put your setup code here, to run once:
key.keyPin = 36;
  pinMode(key.keyPin,INPUT_PULLUP);
  // debug output at 9600 baud
  Serial.begin(9600);
 pinMode(53, OUTPUT);

  // setup SD-card
  Serial.print("Initializing SD card...");
  if (!SD.begin(53)) 
  {
    Serial.println(" failed!");
    return;
  }
  Serial.println(" done.");
  // hi-speed SPI transfers
  SPI.setClockDivider(53);

  // 44100Khz stereo => 88200 sample rate
  // 100 mSec of prebuffering.
  Audio.begin(88200, 100);

}

void loop() {
  // put your main code here, to run repeatedly:


  key.noteAudio = SD.open("test.wav");
  // until the file is not finished
  //Serial.println(digitalRead(key.keyPin));
  if (digitalRead(key.keyPin)==LOW && key_released)
  {   key_released=false; 
    while (key.noteAudio.available()  ) {
    
      //Serial.println("Playing file...");
      // read from the file into buffer
      
      key.noteAudio.read(buffer, sizeof(buffer));
    
      // Prepare samples
      volume = 1024;
      Audio.prepare(buffer, S, volume);
      // Feed samples to audio
      Audio.write(buffer, S);
    
    }
  //  memset(buffer,0,S);
  } 
  key.noteAudio.close();
  if (digitalRead(key.keyPin)==HIGH) key_released=true;
}

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.