I am using JLayer to play my sounds in my game. I am trying to set independent volume levels for my music (constantly playing) and sound effects (sporadic). Right now my code changes the master volume level so, as expected, it changes the volume of both. Here is some sample code to demonstrate what I want to do(I cut a lot of stuff out to try and be SSCCE-like and realize there are some "bugs").
Any help would be hugely appreciated.
public static void playSoundOrMusic(String filename, String type) {
String soundFilename = "";
if (type.equals("SFX")){
soundFilename = "res/sounds/sfx/" + filename;
} else if (type.equals("MUSIC")){
soundFilename = "res/sounds/music/" + filename;
}
FileInputStream fis = null;
try {
fis = new FileInputStream(soundFilename);
} catch (FileNotFoundException e) {
LOGGER.error("Sound file missing", e);
}
BufferedInputStream bis = new BufferedInputStream(fis);
try {
if (type.equals("SFX")){
sfxPlayer = new Player(bis);
} else if (type.equals("MUSIC")){
musicPlayer = new Player(bis);
}
} catch (JavaLayerException e) {
LOGGER.error("Sound file issue", e);
} catch (ArrayIndexOutOfBoundsException e) {
LOGGER.error("Sound file issue", e);
}
if (type.equals("SFX")){
Info source = Port.Info.SPEAKER;
if (AudioSystem.isLineSupported(source)){
try {
Port outline = (Port) AudioSystem.getLine(source);
outline.open();
FloatControl volumeControl = (FloatControl) outline.getControl(FloatControl.Type.VOLUME);
volumeControl.setValue(OptionsJPanel.sfxVolume);
} catch (LineUnavailableException ex) {
LOGGER.error("Sound line issue", ex);
}
new Thread(new Runnable() {
@Override
public void run() {
try {
sfxPlayer.play();
} catch (Exception ex) {
LOGGER.error("Sound(sfx) playing issue", ex);
}
}
}).start();
}
}
if (type.equals("MUSIC")){
Info source = Port.Info.SPEAKER;
if (AudioSystem.isLineSupported(source)){
try {
Port outline = (Port) AudioSystem.getLine(source);
outline.open();
FloatControl volumeControl = (FloatControl) outline.getControl(FloatControl.Type.VOLUME);
volumeControl.setValue(OptionsJPanel.musicVolume);
} catch (LineUnavailableException ex) {
LOGGER.error("Sound line issue", ex);
}
new Thread(new Runnable() {
String threadFilename = filename;
@Override
public void run() {
try {
musicPlayer.play();
while(!musicPlayer.isComplete()){
Thread.currentThread();
Thread.sleep(1000);
}
playSoundOrMusic(threadFilename, type);
} catch (Exception ex) {
LOGGER.error("Sound(music) playing issue", ex);
}
}
}).start();
}
}
}