blembo
blembo

Reputation: 117

Audio playing in Processing not working how I expected

This particular part of my code will show a red line on the screen whenever I hit a key such as the space bar. It also is supposed to play an audio sound "laser" every time a key is pressed. When I first run my processing code and hit spacebar it plays the sound and displays the red line for as long as I hold down the key (as expected). However pressing spacebar a second time only results in a red line appearing and no sound playing. Can someone explain a way to make this work all the time and not just the first time?

import ddf.minim.* ;
Minim minim;
AudioPlayer laser;

void setup()
{
  minim = new Minim(this);     
  laser = minim.loadFile("laser.wav");
}

void draw()
{
  if(keyPressed)
  {
    laser.play(); // Laser sound
    stroke(255,0,0); // Red
    line(337,197,1500,197);  // Laser
  }  
  else
  {
    stroke(255,255,255);  // White
    line(337,197,1500,197); // Cover up the laser
  }
}

Upvotes: 0

Views: 720

Answers (1)

Majlik
Majlik

Reputation: 1082

Playing sounds with minim is like reading a book and you just start reading by lase.play() because your sound is short it will play it whole and than its done. If you want to read/play it again you will have to specify start position.

Basic approach is using laser.rewind() but you could also use more specific function like cue(int millis) for more information read JavaDoc.

Also checking if key is pressed inside draw() for playing music is bad approach and I would recommend using keyboard handlers.

void draw()
{
    stroke(line);
    line(337,197,1500,197);
}

void keyPressed() {
  laser.play();
  line = color(255, 0, 0);
}

void keyReleased() {
 laser.pause(); //pause when key is released
 laser.rewind();
 line = color(255, 255, 255);
}

Upvotes: 1

Related Questions