如何在退出 JFrame 时停止 AudioSystem?

How to stop AudioSystem while exiting JFrame?

我正在制作游戏并向其中添加了音乐。问题是当我关闭游戏时,音乐仍在播放。

播放音乐的脚本:

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

您可能希望使用 WindowListener/WindowStateListener,它允许您注册 JFrame 的关闭、图标化等事件。在里面你当然会暂停,或者开始播放音频。

您可以在 How to Write Window Listeners 上阅读更多内容:

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) {
    }
});