I'm trying to control the volume of a file with keyinput. But all I get is a null error:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException: Cannot invoke "javax.sound.sampled.FloatControl.setValue(float)" because "this.fc" is null
I tried to set it to value cVol but I also get an error, so I think the error is somewhere different.
Here's my sound file. I want to change the volume with the 3 methods below. I used a debug text and the program arrived in the method. So the error is somewhere else. But I can't find it!
public class Sound {
Clip clip;
URL soundURL[] = new URL[30];
float prevVol = 0;
float cVol = 6.0f;
boolean mute = false;
FloatControl fc;
public Sound() {
soundURL[0] = getClass().getResource("/sound/BlueBoyAdventure.wav");
soundURL[1] = getClass().getResource("/sound/coin.wav");
}
public void setFile(int i) {
try {
AudioInputStream ais = AudioSystem.getAudioInputStream(soundURL[i]);
clip = AudioSystem.getClip();
clip.open(ais);
fc = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN);
fc.setValue(cVol);
}catch (Exception e) {
}
}
public void volUp() {
cVol += 1.0f;
System.out.println("up");
if(cVol > 6.0f) {
cVol = 6.0f;
}
fc.setValue(cVol);
}
public void volDown() {
cVol -= 1.0f;
if(cVol > -80.0f) {
cVol = -80.0f;
}
fc.setValue(cVol);
}
public void mute() {
if(mute == false) {
prevVol = cVol;
cVol = -80.0f;
fc.setValue(cVol);
mute = true;
}else if(mute == true) {
cVol = prevVol;
fc.setValue(cVol);
mute = false;
}
}
}
My keyHander. I want to control the volume with 0,9,8:
if(code == KeyEvent.VK_8) {
s.volUp();
gp.ui.addMsg("volume up");
}
if(code == KeyEvent.VK_9) {
s.volDown();
gp.ui.addMsg("volume down");
}
if(code == KeyEvent.VK_0) {
s.mute();
gp.ui.addMsg("volume muted");
}
```
setFilefunction has not run to completion to initializefc, or that thatcliphas noFloatControlof typeMASTER_GAIN, sogetControl()is returningnull. I'm not sure why that would be the case, but since you seem to be loading it from a file, one speculative possibility is that the clip hasn't finished loading yet. \$\endgroup\$clip&fcto see if they are initializing properly. \$\endgroup\$