问题
I have some music playing in my program. I want it to switch music depending on certain actions etc. The problem is I have my music begin playing from one method and I am trying to stop it from another method or action event. The other method isnt able to find my clip object because it is not public. Is it possible to make this clip object public for my whole class? I tried making another class just for music. Could someone guide me? Thanks,
public void playsound(String filepath){
try {
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File(filepath));
Clip clip = AudioSystem.getClip( );
clip.open(audioInputStream);
clip.start( );
}
catch(Exception e) {
e.printStackTrace( );
}
}
public void dummyMethod(){
//when this method is call make the clip stop
}
回答1:
Why don't you make the Clip
object an instance/class-wide variable instead of just a local variable, so you can call a clip.stop()
or clip.pause()
method when you want to turn it off or pause it?
EDIT
// declare as an instance variable
private Clip clip;
public void playsound(String filepath){
try {
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File(filepath));
// NOTICE: I am only initializing and NOT declaring (no capital Clip)
clip = AudioSystem.getClip( );
clip.open(audioInputStream);
clip.start( );
}
catch(Exception e) {
e.printStackTrace( );
}
}
// call stop method to stop clip form playing
public void dummyMethod(){
clip.stop();
}
回答2:
Make Clip clip
a class variable then call the clip.Stop()
from dummyMethod
回答3:
Declare your Clip variable outside the methods,
Just write Clip clip; above your methods,
来源:https://stackoverflow.com/questions/21369365/how-to-stop-a-sound-while-its-playing-from-another-method