so I've been working on my game library and I just got working on the sound aspect of it. But the problems are that the Sound starts playing from the constructor instead of the play method and also the stop doesn't work for the constructor and only the play method.
I tried debugging the code but I didn't get any results from it. I also tried using the stop method before doing the play method but that didn't work either
below is the code,
import java.io.*;
import java.io.File;
import java.io.IOException;
import javax.sound.sampled.*;
// class stuff
private Clip clip;
private FloatControl fc;
public SoundLoader(File file) {
try {
InputStream audioSource = new FileInputStream(file);
InputStream bufferedInput = new BufferedInputStream(audioSource);
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(bufferedInput);
AudioFormat baseFormat = audioInputStream.getFormat();
AudioFormat decodedFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,
baseFormat.getSampleRate(),
baseFormat.getSampleSizeInBits(),
baseFormat.getChannels(),
baseFormat.getFrameSize(),
baseFormat.getFrameRate(),
false
);
AudioInputStream decodedAudioInputStream = AudioSystem.getAudioInputStream(decodedFormat, audioInputStream);
clip = AudioSystem.getClip();
clip.open(decodedAudioInputStream);
fc = (FloatControl)clip.getControl(FloatControl.Type.MASTER_GAIN);
} catch (UnsupportedAudioFileException | IOException | LineUnavailableException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void play(boolean loop){
if(clip == null || isRunning())return;
stop();
while(!clip.isRunning())
clip.start();
if(loop)clip.loop(Clip.LOOP_CONTINUOUSLY);
}
and here is an example of what's happening in log form,
clip starts running from constructor
same clip starts running from play method
stop method stops the clip from running from the play method
constructor keeps on playing
If anyone knows why this is happening it would be nice if you could reply to this. Thanks
edit: I changed clip and fc to not static because I use testing something out with static and then I forgot to change it back to normal
okay I solved it. It was just a case of me blacking out while I was coding and I was playing the sound in the main method of the project. I'm glad that it wasn't a problem with the Clip class