Interaction Design WikiCreative Coding

Sound

Processing is not distributed with sound features built in, but you can use sound by installing a library. The Sound libraries need to be downloaded through the Library Manager. go to the "Sketch" menu and select "Add Library..." from the "Import Library..." submenu. 

Use the search feature to find and install the "minim" sound library. 


http://code.compartmental.net/tools/minim/quickstart/

sound code
import ddf.minim.*;

Minim minim;
AudioSample sound1; //audio samples are kept in a buffer. They are suitable for shorter sounds
AudioPlayer player; //Audio player loads the sound on the fly. This is suitable for background music or longer audio clips

void setup() {
  size(600, 300);
  // sound init
  minim = new Minim(this);
  sound1 = minim.loadSample("soundFile1.mp3");
  player = minim.loadFile("soundFile2.mp3");
}

void draw() {
  //circle 1
  background(100);
  noStroke();
  fill(255);
  ellipse(200, height/2, 40, 40);
  //circle 2
  if (player.isPlaying()) {
    fill(255, 0, 0);
  } else {
    fill(255);
  }
  ellipse(400, height/2, 40, 40);
}; 

void mousePressed() {
  //circle 1
  if (overCircle(200, height/2, 40)) {
    println("circle 1");
    sound1.trigger();
    fill(255, 0, 0);
    ellipse(200, height/2, 40, 40);
    fill(255);
  }
  //circle 2
  if (overCircle(400, height/2, 40)) {
    println("circle 2");
    jukeBox();
  }
}

boolean overCircle(int x, int y, int diameter) {
  //check if mouse is over the circle 
  if (dist(x, y, mouseX, mouseY) <= diameter) {
    return true;
  } else {
    return false;
  }
}

void jukeBox() {
  //toggle sound on and off
  if ( player.isPlaying() )
  {
    player.pause();
  } else  {
    player.play();
  }
  // if the player reaches the end of the file,
  // it must be rewound to the start again before being replayed.
  if ( player.position() == player.length() )
  {
    player.rewind();
    player.play();
  } 
}

Download the source files: 

sound.zip