How to interrupt a playing audio file?


I have the following code to play a 30 sec audio file (phone ring), I want it to stop the audio when line 2 goes low. The code I have waits for the audio clip to finish, how can I interrupt the audio play routine on change of input state?

include "SD.h" //SD Card Library
#include "TMRpcm.h" //Audio Library
#include "SPI.h" //SD SPI library
#define SD_ChipSelectPin 4 //Chip select is pin number 4
TMRpcm play_audio; 

void setup(){

play_audio.speakerPin = 9;  //Auido Out on pin 9
Serial.begin(9600);         //Serial Com for debugging
if (!SD.begin(SD_ChipSelectPin)) {
Serial.println("SD fail");

pinMode(2, INPUT_PULLUP);   // Handet Onhook/Offhook Detection
play_audio.quality(2);      //  Set 1 for 2x oversampling Set 0 for normal


void loop()

  Serial.print("RING RING");

    if (digitalRead(2)==LOW)              // Handset has been Lifted
      Serial.println("OFF-HOOK");    "hello.wav");    
      Serial.println("PLAYING MSG-1"); 
    delay (25000);
    goto a;


I would do two things:

  1. Get rid of GOTO, there’s no reason for that here.
  2. Use the stopPlayback() command to stop the RING RING sound when your digitalRead() is true.

Ditch that goto. Now. It's not just ugly, it's totally redundant. Then go and shoot your teacher for even teaching you about the existence of this command at beginner's level.

Next ditch that lengthy delay() call.

And you're in much better shape already. It's simply a matter of using state change detection on your phone hook and start/stop playing the sound based on that. See the built-in StateChangeDetection example sketch.


I have doubts that you really want to end up in an infinite loop.

@dudester, do not cross-post. Threads merged.

Next ditch that lengthy delay() call.

Thats how i had it originally but found it tries to play the audio over and over too fast and no actual sound is generated, adding the delay was the only way i could let the audio clip play.
Is there a better way to be coding this audio play?

Again: state change detection.

You start playing audio when the pin goes low, not when it is low. Likewise you stop playing when the pin goes high.

wvmarle: Again: state change detection.

I dont understand how to code for that...

dudester: I dont understand how to code for that...

Then look at the state change example in the Arduino’s IDE.

Between #6 and #8 my comment #2 has been duplicated. Hope OP actually reads (and acts upon) the replies...