3

I already have a working method to play sound effects in my game, but the sounds are all played at the default volume. I want a sound to be more quiet if the distance between the sound effect's origin and the player increases.

Currently I'm using:

public static void play(String sound) {
    Clip clip = soundList.get(sound);
    clip.setFramePosition(0);
    //I want to set the clip's volume here
    clip.start();
}

There is something like clip.getLevel(), but there is no setter. How can I set the clip's volume before it starts?

Thanks in advance!

Rapti
  • 2,520
  • 3
  • 20
  • 23
  • 1
    I think you can look at http://stackoverflow.com/questions/953598/audio-volume-control-increase-or-decrease-in-java where they reduce the volume. Of course, you'd just add to the volume. – Ewald May 18 '12 at 10:22
  • if multiple clips overlap, possibly with other sounds, like system sounds, that won't work. – Bjorn Roche May 20 '12 at 17:26

2 Answers2

1

In Java 7 (and maybe Java 6), there is a set of classes that give control to the clip. These are:

  • Boolean Control
    • Mute
    • Apply/Remove Reverb
  • Compound Control
  • Enum Control
    • Reverb Controls
  • Float Control
    • Auxiliary Return
    • Auxiliary Send
    • Balance
    • MASTER GAIN
    • Panning
    • Reverb Return
    • Reverb Send
    • Sample Rate
    • VOLUME

The control object you are looking for is the FloatControl. As shown in the list above, this can control the volume of your clip. Implement this by using the following code:

FloatControl volume = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN);
volume.setValue(gainAmount);

-OR-

((FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN)).setValue(gainAmount)

Where gainAmount is the amount of decibels you want to raise (or lower) your clip by.

TheBrenny
  • 528
  • 3
  • 19
0

The clip API does not support this, AFAIK. I think you'll have to read the raw data, multiply by a constant, and create a new clip using the raw data. The constant represents the volume change amount, so if you want it to be half as loud, multiply by .5.

If you want to make something louder, you'll have to watch out for "overs". There's no simple way to deal with that.

Bjorn Roche
  • 11,279
  • 6
  • 36
  • 58