Main Sketch
Ball[] b = new Ball[10];
SoundPlayer sp;
void setup() {
//size(1000,1000);
sp = new SoundPlayer(this, "beep.ogg");
for (int i = 0; i < b.length; i++)
{
b[i] = new Ball(int(random(10,100)), color(int(random(0,255)),int(random(0,255)),int(random(0,255))),
int(random(0,width)),int(random(0,height)),int(random(0,10)),int(random(0,10)),width,height);
}
}
void draw() {
background(255,255,255);
for (int i = 0; i < b.length; i++)
{
b[i].draw();
}
}
void mousePressed() {
sp.play();
}
Ball Class
class Ball {
int myRadius;
color myColor;
int x;
int y;
int directionX;
int directionY;
int w, h;
public Ball(int r, color c,
int _x, int _y,
int dx, int dy, int w, int h) {
myRadius = r;
myColor = c;
x = _x;
y = _y;
directionX = dx;
directionY = dy;
this.w = w;
this.h = h;
}
void bounceX() {
directionX = directionX * -1;
}
void bounceY() {
directionY = directionY * -1;
}
void update() {
if (x < myRadius/2 || x > w-myRadius/2) {
bounceX();
}
if (y < myRadius/2 || y > h-myRadius/2) {
bounceY();
}
x = x + directionX;
y = y + directionY;
}
void draw() {
update();
ellipseMode(CENTER);
fill(myColor);
ellipse(x,y,myRadius,myRadius);
}
}
SoundPlayer Class
class SoundPlayer extends Object implements android.media.MediaPlayer.OnCompletionListener {
android.media.MediaPlayer mediaPlayer;
android.content.res.AssetFileDescriptor assetFileDescriptor;
processing.core.PApplet theSketch;
boolean ready = false;
public SoundPlayer(PApplet _theSketch, String audioFile) {
theSketch = _theSketch;
try {
assetFileDescriptor = theSketch.getAssets().openFd(audioFile);
mediaPlayer = new android.media.MediaPlayer();
mediaPlayer.setDataSource(assetFileDescriptor.getFileDescriptor(),assetFileDescriptor.getStartOffset(), assetFileDescriptor.getLength());
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.prepare();
ready = true;
} catch (Exception e) {
println(e);
}
}
public void play() {
if (ready) {
try {
mediaPlayer.start();
ready = false;
println("playSound");
} catch (Exception e) {
println(e);
}
}
}
public void onCompletion(android.media.MediaPlayer mp) {
try {
println("Trying to prepare");
mediaPlayer.stop();
mediaPlayer.prepare();
ready = true;
}
catch (Exception e) {
println(e);
}
}
}