Home>

I am using Keypressed to make a code that produces sound. I want to stop the previously pressed key and play the next sound when a different key is pressed while the pressed key sounds. Please tell us what kind of code you should use.

When the "o" key is pressed while the "p" key is pressed and the sound is playing, the "p" sound stops and the "o" starts to sound.

Applicable source code

import ddf.minim.*;

Minim minim;
AudioPlayer song1,song2,song3,song4;

void setup()
{
minim = new Minim(this);
song1 = minim.loadFile("/Users/raku/Desktop/sample/STE-117.wav");
song2 = minim.loadFile("/Users/raku/Desktop/sample/STE-119.wav");
song3 = minim.loadFile("/Users/raku/Desktop/sample/STE-120.wav");
song4= minim.loadFile("/Users/raku/Desktop/sample/STE-122.wav");
}

void draw()
{
}

void keyPressed()
{
if (key =='p')
{
song1.play();
}
if (key =='o')
{
song2.play();
}

if (key =='i')
{
song3.play();
}

if (key =='u')
{
song4.play();
}
}

void stop()
{
song1.close();
song2.close();
song3.close();
song4.close();
minim.stop();
super.stop();
}

Supplementary information (FW/tool ​​version, etc.)

Processing 3.5.4

  • Answer # 1

    When a different key is pressed

    How do you look for "different"? You just have to find out if the key that was pressed so far is the same as the key that was pressed. The key that was just pressed can be obtained with key, so what is the key that has been pressed so far? The value that the key of the previous time had.

    So, for example
    char prevKey;
    And let's set a variable to hold the previous key.

    void keyPressed(){
      if( prevKey!=key ){ // Was a different key pressed?
        if (key =='p')
          song2.pause();// stop the previously pressed key
          song3.pause();
          song4.pause();
          song1.rewind();
          song1.play();// I want to play the next sound
        }
      <Omitted>
      }
      prevKey=key;// The current key will be the "key that was pressed just before" next time
    }