How do I break serial/audio output loop?

I’m having problems with having an RFID tag scanned and triggering an audio file. Every time I scan an RFID tag the audio constantly plays multiple instances at once, creating a Doppler effect. I did println(file.isPlaying()); and it came up with multiple outputs of true. The goal is to scan multiple RFID tags and each tag to trigger an image and audio to play once. How do I stop it from playing multiple times at once?

Here is my processing code:

import processing.serial.*;
import processing.sound.*;

Serial myPort;          // The serial port  
String finalRead = "";  // Variable with final data  
String inputRead = "";  // Variable that receives the data  
int state = 0;          // Variable to store the program state  
PImage img;             // Variable for images
SoundFile file;       // Variable for audio

void setup() {
  
  fullScreen();
  printArray(Serial.list());
  myPort = new Serial(this, Serial.list()[0], 9600);
  
}

void draw() {

  while (myPort.available() > 0)
  {

    char c=(char)myPort.read();

    if (c=='\n')
    {
      finalRead = inputRead;
      inputRead = ""; 
      println("data: " + finalRead);
    } else if (c!='\r')
    {
      inputRead+=c;
    }
  } 

  if (finalRead.equals("E9621895")) {
    state = 1;
  }

  if (finalRead.equals("DA07CA24")) {
    state = 2;
    
  }
    if (state == 1) {
      background (0);
      img = loadImage ("new1.jpg");
      image (img, 0,0);
    file = new SoundFile(this, "new1.wav");
    file.play();

  }
  
    if (state == 2) {
      background (0);
      img = loadImage ("new2.jpg");
      image (img, 0,0);
    file = new SoundFile(this, "new2.wav");
    file.play();
  }
}
1 Like

your program flow is wrong,

the draw loop runs 60 times per sec,

in case state is 1
you try to load a file and start a song
60 times per sec.

so you get that that can not work.
need kind of event thinking.

also loading files better do once i n setup
to song1 and song2

1 Like