[英]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? 为什么不使Clip
对象成为实例/类范围的变量,而不仅仅是局部变量,所以当您要关闭或暂停它时可以调用clip.stop()
或clip.pause()
方法?
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, 在方法之外声明Clip变量,
Just write Clip clip; 只需编写Clip剪辑; above your methods, 在您的方法之上,
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.