Reputation: 31
I need to make an audio player that plays a sound clip whenever this subroutine is run. It must also stop the previous sound clip before playing the new one.
The issue I'm having is that the clip is never registered as running. Neither of the two if statements that check to see if it is running are ever used. This means the clip only stops when it is finished, and s they can overlap, and ruin the program.
I would use clip.stop(); in other subroutines, but it will tell me that the 'clip' symbol cannot be found. I don't know how to make it available for other subroutines to use.
The only way I can get clip.stop(); to work in this subroutine is by placing it straight after the clip.start(); line, which stops the clip immediately after starting, so it isn't heard at all.
Below is the subroutine I'm using to play audio clips.
public void play(String filename){
try {
Clip clip = AudioSystem.getClip();
audFile = audDir + filename;
if (clip.isRunning()){
System.out.println("Sounds playing 1");
clip.stop();
}
clip.open(AudioSystem.getAudioInputStream(new File(audFile)));
clip.start();
if (clip.isRunning()){
System.out.println("Sounds playing 2");
clip.stop();
}
} catch (Exception exc) {
exc.printStackTrace(System.out);
}
}
Upvotes: 3
Views: 1912
Reputation: 2899
I would use clip.stop(); in other subroutines, but it will tell me that the 'clip' symbol cannot be found. I don't know how to make it available for other subroutines to use.
Declare a private Clip field in your class
private Clip clip;
and set it when you get it from AudioSystem.getClip()
.
/*
* clip (local variable) is invisible from other methods
*/
Clip clip = AudioSystem.getClip();
this.clip = clip; // `this.clip` is a field, it's visible from other methods
Then you can access it from other methods ("subroutines" are class methods in Java).
The issue I'm having is that the clip is never registered as running.
It is not running when you call clip.isRunning()
, but are you sure it is never running?
You can't assume that clip.isRunning()
returns true
right after clip.start()
. The mechanism being asynchronous, it might help to register a LineListener
and listen to the START
event.
clip.start();
LineListener listener = new LineListener() {
public void update(LineEvent event) {
if (event.getType() == LineEvent.Type.START) {
/*
* here you are sure the clip is started
*/
}
}
};
clip.addLineListener(listener );
Upvotes: 1