如何停止播放 JAVA 中的 WAV 剪辑

问题描述

我试图在按下开始按钮时停止播放前奏曲。我尝试使用此代码这样做。请注意,此代码并不包含我的所有代码。 GUI 看起来不错,Actionlistener 也可以正常工作。只有按下开始按钮时音乐不会停止播放

File introPath = new File("src/BattleshipGUI/423499__soundflakes__epic-heroic-orchestral- 
                                                                      dramatic.wav");
File buttonPressedPath = new File("src/BattleshipGUI/sfx_patcher_button_launch.wav");
static Clip introWAV;


    Menu() {


    super("BattleBoard");


    this.setContentPane(this.panelMain);
    this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    this.setLocationRelativeTo(null);
    this.pack();
    
    play(introPath); // playing when launching 


    // when the game starts,the sound should stop

    ButtonStartGame.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            super.mouseClicked(e);
            play(buttonPressedPath);

            try {
                if (random) {

                    currentCols = (Integer) spinnerColumns.getValue();
                    currentRows = (Integer) spinnerRows.getValue();
                    if (currentCols < 5 || currentRows < 5) {
                        
                        throw (new IllegalArgumentException());
                    } else {
                        BoardFrame b = new BoardFrame(currentRows,currentCols);
                        b.SetFrame(currentRows,currentCols);
                        b.AddRandomShips(currentRows,currentCols);
                        b.ScoreMethod(adjustedScoreMethod);
                        introWAV.stop();
                        introWAV.flush();
                        introWAV.close();
                        dispose();



public static void SetIntroWAV(Clip clip){

    introWAV=clip;
}

public static void play(File file) {
    try {
        Clip sound = AudioSystem.getClip();
        sound.open(AudioSystem.getAudioInputStream(file));
        SetIntroWAV(sound);
        sound.start();

    } catch (Exception e) {
        System.out.println(e);
    }
}

我尝试了其他方法,比如在 Play 类中使​​用 while 循环、'if-else'-语句、...有人知道如何解决这个问题吗?提前致谢!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)