简体   繁体   中英

How to stop a sound (while its playing) from another method

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
}

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();
 }

使Clip clip成为类变量,然后从dummyMethod调用clip.Stop()

Declare your Clip variable outside the methods,
Just write Clip clip; above your methods,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM