如何在退出jframe时停止audiosystem?

20jt8wwn  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(338)

我在做一个游戏,我在里面放了音乐。问题是当我关闭游戏时,音乐还在播放。
播放音乐的脚本:

try {
        clip1 = AudioSystem.getClip();
        try {
            clip1.open(AudioSystem.getAudioInputStream(music));
        } catch (IOException | UnsupportedAudioFileException e) {
            e.printStackTrace();
        }
        if (!Settings.Music) {

            return;
        }
        clip1.start();
    } catch (LineUnavailableException e) {
        e.printStackTrace();
    }

循环播放音乐的脚本:

public static void tick() {

    if (clip1.isRunning()) {

        if (!Settings.Music) {

            clip1.stop();
            // this makes music stop when player changes settings 
        }
    }

    if (Settings.Music) {
        if (!clip1.isRunning()) {

            playMusic(Game.music1);
        }
    }
}
ndasle7k

ndasle7k1#

你应该用 WindowListener / WindowStateListener 它允许您注册的事件,如关闭,图标化等 JFrame . 在里面,你当然会暂停,或启动音频。
您可以在此处阅读有关如何编写窗口侦听器的更多信息: WindowStateListener 示例(可能是最简单的,也没有那么详细,允许您比较以前的和新的状态,还有许多其他windowevent选项要检查):

frame.addWindowStateListener((WindowEvent e) -> {
     if (e.getNewState() == WindowEvent.WINDOW_CLOSED 
        || e.getNewState() == WindowEvent.WINDOW_ICONIFIED) {
        // TODO stop the audio when window is closed or iconified (minimzed)
     }
 });
``` `WindowListener` 示例(更详细一点,但为了完整起见):

frame.addWindowListener(new WindowListener() {
@Override
public void windowOpened(WindowEvent e) {
}

@Override
public void windowClosing(WindowEvent e) {
}

@Override
public void windowClosed(WindowEvent e) {
}

@Override
public void windowIconified(WindowEvent e) {
}

@Override
public void windowDeiconified(WindowEvent e) {
}

@Override
public void windowActivated(WindowEvent e) {
}

@Override
public void windowDeactivated(WindowEvent e) {
}

});

相关问题