Playing multiple audio files in sequence with 1 push button

Hi there all,
I’ve just started learning c++ within the arduino IDE.
Trying to get my teensy v3.1 to playback 3 different sound files.
The first to be played once when the button is pushed in.
The second to then be played in a loop while the button is held down.
The third to be played once when the button is released.
Btw I’m not actually using the Audio shield.
The board is being powered by a 3v coin cell as is the miniature amplifier.
My code compiles but doesn’t seem to work as desired.

#include <Audio.h>
#include <Wire.h>
#include <SPI.h>
#include <SD.h>
#include “mngs1.h”
#include “mngs2.h”
#include “mngs3.h”

AudioPlayMemory gunSound; // creates the Audio memory object
AudioOutputAnalog dac; // play to on-chip DAC
AudioConnection c1(gunSound, 0, dac, 0);
AudioControlSGTL5000 audioShield;
int inPin = 2;
int val = 0;

void setup()
{
pinMode(2, INPUT); //Sets the digital pin as input:
AudioMemory(1); //Allocates 1 memory spaces for audio file to be played

// turn on the output
audioShield.enable();
audioShield.volume(0.5);
}

void loop()
{
val = (digitalRead(inPin));
if (val == HIGH)
{
gunSound.play(mngs1);
}
if (!gunSound.isPlaying())
{
val = (digitalRead(inPin));
while (val == HIGH)
{
if (gunSound.isPlaying())
{
val = (digitalRead(inPin));
}
gunSound.play(mngs2);
}
}
if (val == LOW)
{
gunSound.play(mngs3);
}
};

Please let me know if I’ve made any booboos with what I’m trying to achieve.

StrangeOne:
Btw I'm not actually using the Audio shield.

What are you using then? Do you want to use the Cortex M4 DAC?

My code compiles but doesn't seem to work as desired.

What's not working? Or what IS actually working? :wink:

You need to detect edges in the signal not levels like you are doing.
Remember that the loop function should repeat many hundreds of times a second.
Make a note of the state of the switch in a variable such as lastVal at the end of the loop.
Then only trigger the first sound when the current val indicates pressed and the lastVal indicates unpressed.

Do a similar thing for the release.

Then for the sustain, set a variable when you trigger the first sound and only trigger the sustain sound when the current val is showing pressed and the variable indicates the first sound has been played and the sustain sound is not playing.

Your code will look very different from the long chain of if statements that you have now that are all too easy to get wrong, as you have found.