Hello there,
I creating a sound engine for my 2D game, where i want to change pan and gain in each sound, so i create class, that have minim AudioSample, that loads specific sound, but when i want to delete this, it cant remove the sound file from RAM, i think… and when you play lots of sounds, RAM goes very high and overfill…
static final float NON_AUDIBLE_GAIN = -100.0;
import ddf.minim.*;
import ddf.minim.ugens.*;
Minim minim;
AudioOutput out;
ArrayList<Sound> sounds = new ArrayList<Sound>();
PVector listener;
Sound shoot;
void setup() {
size(640, 360);
minim = new Minim(this);
out = minim.getLineOut();
listener = new PVector(width/2, height/2);
shoot = new Sound("shoot.mp3");
ellipseMode(CENTER);
}
void draw() {
background(0);
for (int i = sounds.size()-1; i >= 0; i--) {
Sound s = sounds.get(i);
float amplitude = map(constrain(dist(listener.x, listener.y, s.pos.x, s.pos.x), 0, s.dist), 0, s.dist, s.maxAmp, s.minAmp);
float panning = map(s.pos.x, listener.x-s.dist, listener.x+s.dist, -1, 1);
// IF IS THE SOUND OUT OF LISTENER
if (dist(listener.x, listener.y, s.pos.x, s.pos.y) < s.dist) {
s.sample.unmute();
} else {
s.sample.mute();
}
// SET PAN AND GAIN OF SOUND
s.gain = amplitude;
s.pan = panning;
// DRAW A RANGE (DISTANCE)
noFill();
stroke(0, 0, 255);
ellipse(s.pos.x, s.pos.y, s.dist*2, s.dist*2);
sounds.get(i).refresh();
if (sounds.get(i).remove) {
sounds.remove(i);
}
}
noStroke();
fill(255, 0, 0);
ellipse(listener.x, listener.y, 30, 30);
textAlign(LEFT, TOP);
text(frameRate + "\n" + sounds.size() + "\n", 0, 0);
if (mousePressed) {
playSound(shoot, mouseX, mouseY);
}
}
class Sound {
PVector pos = new PVector();
float dist = 200;
float minAmp = -30;
float maxAmp = 0;
float pan;
float gain;
AudioSample sample;
int deadTime;
boolean remove = false;
String path;
Sound(String path) {
this.path = path;
sample = minim.loadSample(path, 512);
}
void refresh() {
sample.setGain(gain);
sample.setPan(pan);
fill(0, 255, 0);
ellipse(pos.x, pos.y, 30, 30);
if (deadTime < millis()) {
remove = true;
// I TRYES TO NULL EVERYTHINKS... NOTHINK HELPS...
sample.stop();
sample = null;
path = null;
pos = null;
}
}
void play() {
deadTime = millis() + sample.length();
sample.trigger();
}
Sound setDist() {
return this;
}
}
void playSound(Sound soundFile, float x, float y) {
sounds.add(new Sound(soundFile.path));
sounds.get(sounds.size()-1).pos = new PVector(x, y);
sounds.get(sounds.size()-1).play();
}
Lets try it…
How to do it better ? Is there any better library ? Is the way ? Thanks, George.