public void playMet() {
int tempo = Integer.parseInt(met_speed.getText());
tempo = tempo/60;
int delay = tempo*1000;
if(Play.isSelected()) {
try {
FileInputStream in = new FileInputStream(new File("Click1.wav"));
AudioStream as = new AudioStream(in);
AudioPlayer.player.start(as);
Thread.sleep(tempo*1000);
playMet();
}
catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
else
System.out.println("not playing");
}
这是我的代码的一部分,基本上当按下按钮时,它每分钟播放一次X次。
我已尝试使用这样的while循环代码:
while(Play.isSelected()) {
.........
.........
}
那也没有用。在这两种情况下,程序都应该运行,但冻结,我必须从任务管理器关闭它。
如何在按下按钮时调用某个功能,如果取消选择它可以停止它?
P.S。刚看到下面的两个帖子。必须去上班,稍后会检查它们,看看它们是否有效。谢谢你的帮助。
答案 0 :(得分:1)
递归调用阻止了Event Dispatch Thread。你必须创建一个新的线程来阻止EDT。
public void playMet()
{
Thread t = new Thread(new Runnable()
{
@Override
public void run()
{
while(Play.isSelected()){
//Your code
}
}
};
t.start();
}
答案 1 :(得分:1)
你不需要Thread.sleep(),你不需要递归或while循环。 你需要有状态的球员。而你的UI应该只改变播放器的状态。
查看https://stackoverflow.com/a/7524627/2078908
中的示例private final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
private ScheduledFuture<?> playingTask;
private FileInputStream playing;
public void playMet() {
stopPlaying();
playingTask = executor.scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
playMet();
}
}, 0, 1000, TimeUnit.MILLISECONDS);
}
public void playMetOnce(){
try {
IOUtils.close(playing);
playing = new FileInputStream(new File("Click1.wav"));
AudioStream as = new AudioStream(playing);
AudioPlayer.player.start(as);
} catch (Exception e)
{
JOptionPane.showMessageDialog(null, e);
}
}
public void stopPlaying(){
try {
AudioPlayer.player.stop();
IOUtils.close(playing);
playing = null;
if (playingTask != null) {
playingTask.cancel(false);
}
playingTask = null;
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}