Loading...
Logo
Processing Forum
I am using the ESS sound library to play sound effects in a game. Every time a sound is played, an audio channel is created, the sound is loaded in, the channel plays, and the channel is deleted.

 The problem with this method is that the audio file have to be pulled of the disk every time a sound needs to be played. I cannot just have one channel for each sound effect either, because then the sounds will be unable to play in rapid succession.

Here is my current audio class. I'm sure there is a much better way to play sounds, but I'm fairly new to OOP, and I can't think of a better way.
class Audio {   void playSound(int selected, float volume) { //loads a sound into a channel     myChannel = (AudioChannel[])expand(myChannel, myChannel.length + 1); //expand the array to
make room for the new audio track
    myChannel[myChannel.length - 1] = new AudioChannel(selected + ".mp3"); //add the new rack          myChannel[myChannel.length - 1].volume(volume); //set the volume     myChannel[myChannel.length - 1].play(); //play the channel     myChannel[myChannel.length - 1].cue(1); //increase the cue, to fix a problem where the cue
 reads "0" for the first frame, setting off the terminator   }      void advance() { //runs every frame     for (int i = 0; i < myChannel.length; i++) { //run for every channel              if(myChannel[i].cue == 0) { //if the channel has finished playing...         myChannel = (AudioChannel[])subset(myChannel,1,myChannel.length - 1); //delete the channel       }     }   } } 

Thanks for any help!

Replies(2)

Your code is messed up...

The idea is indeed to put all the AudioChannel objects in an array created at startup time, in setup. Thus, it should avoid to load the files on each usage. (I think. Might depend on ESS, which I don't use.) Beware of an out of memory error, though.
Ok, I thought up a great solution, which is to simply stop a channel before playing. I can't believe I hadn't thought of it wile writing the class, but then, I was half asleep.


class Audio {
  AudioChannel[] myChannel = new AudioChannel[32];
  
  void playSound(int selected, float volume) { //loads a sound into a channel
    myChannel[selected].stop(); //stop anything already playing
    myChannel[selected].volume(volume); //set the volume
    myChannel[selected].play(); //play the channel
  }
  
  void initilize() {
    myChannel[0] = new AudioChannel("1.mp3"); //add the new rack
    myChannel[1] = new AudioChannel("2.mp3");
  }
}