如何通过另一种方法停止声音(在播放时) [英] How to stop a sound (while its playing) from another method

查看:31
本文介绍了如何通过另一种方法停止声音(在播放时)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的程序中正在播放一些音乐.我希望它根据某些动作等来切换音乐.问题是我让音乐从一种方法开始播放,而我试图从另一种方法或动作事件中停止播放.另一个方法无法找到我的剪辑对象,因为它不是公共的.是否可以在整个课堂上公开此剪辑对象?我试着再听一堂音乐课.有人可以指导我吗?谢谢,

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
}

推荐答案

为什么不将 Clip 对象设置为实例/类范围的变量,而不仅仅是局部变量,所以您可以要关闭或暂停它时,调用 clip.stop() clip.pause()方法?

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?

编辑

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

这篇关于如何通过另一种方法停止声音(在播放时)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆