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

筅森魡賤 提交于 2021-01-29 06:20:49

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!