java - 打开新 JFrame 时停止音乐

标签 java swing javasound

在我的应用程序中,我向主框架添加了一些音乐。如果我单击此框架上的 Jbutton,它将打开一个新的 Jframe,但我的问题是当我打开新的 JFrame 时,音乐仍然继续播放,但我希望它在新的 Jframe 打开时停止

我的主类代码:

package View;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionListener;
import java.io.File;


import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;

import javax.swing.JPanel;

import Controller.HomeController;


import music.PlaySound;

public class Home extends JFrame {

    private JLabel label, label1, label2;
    private JPanel panel;
    private JButton logo, logo1, logo2, logo3, logo4, logo5, selectie;
    private Container window = getContentPane();
    private HomeController Controller;

    public Home (){
        initGUI();

    }
    public void addHomeListener(ActionListener a){
        selectie.addActionListener(a);
    }
    public void initGUI(){
        PlaySound sound = new PlaySound();
        setLayout(null);
        setTitle("");
        setPreferredSize(new Dimension(800,600));
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        label = new JLabel();       
        label.setBounds(0, 0, 266, 800);
        label.setBackground(Color.WHITE);
        label.setOpaque(true);
        window.add(label);

        label1 = new JLabel();
        label1.setBounds(267, 0, 266, 800);
        label1.setBackground(Color.RED);
        label1.setOpaque(true);
        window.add(label1);

        label2 = new JLabel();
        label2.setBounds(533, 0, 266, 800);
        label2.setBackground(Color.WHITE);
        label2.setOpaque(true);
        window.add(label2);

        logo = new JButton(new ImageIcon("../Ajax/src/img/logotje.gif"));
        logo.setBorderPainted(false);
        logo.setBounds(40, 150, 188, 188);
        label1.add(logo);

        logo1 = new JButton(new ImageIcon("../Ajax/src/img/Ster.png"));
        logo1.setBorderPainted(false);
        logo1.setBounds(10, 50, 82, 82);
        label1.add(logo1);

        logo2 = new JButton(new ImageIcon("../Ajax/src/img/Ster.png"));
        logo2.setBorderPainted(false);
        logo2.setBounds(92, 20, 82, 82);
        label1.add(logo2);

        logo3 = new JButton(new ImageIcon("../Ajax/src/img/Ster.png"));
        logo3.setBorderPainted(false);
        logo3.setBounds(174, 50, 82, 82);
        label1.add(logo3);

        logo4 = new JButton(new ImageIcon("../Ajax/src/img/shirt.png"));
        logo4.setBorderPainted(false);
        logo4.setBounds(50, 50, 135, 182);
        label.add(logo4);

        logo5 = new JButton(new ImageIcon("../Ajax/src/img/uitshirt.png"));
        logo5.setBorderPainted(false);
        logo5.setBounds(65, 50, 138, 190);
        label2.add(logo5);

        selectie = new JButton("Selectie");
        selectie.setBounds(60, 500, 99, 25);
        selectie.setActionCommand("selectie");
        label.add(selectie);

        pack();

           Controller = new HomeController(this);
            addHomeListener(Controller);

            setVisible(true);
        }

    public static void main(String... args)
    {
        javax.swing.SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                new Home();
            }
        });
    }

} 

单击按钮时我新打开的 Jframe 的代码:

package View;

import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;

import music.PlaySound;

import Controller.HomeController;

public class Selectie extends JFrame{

    private JLabel label, label1, label2;
    private JButton keeper;
    private JPanel panel;
    private Container window = getContentPane();

    public Selectie()
    {
        initGUI();
    }

    public void initGUI()
    {
        setLayout(null);
        setTitle("");
        setSize(800,600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        label = new JLabel();       
        label.setBounds(0, 0, 266, 800);
        label.setBackground(Color.RED);
        label.setOpaque(true);
        window.add(label);

        label1 = new JLabel();
        label1.setBounds(266, 0, 266, 800);
        label1.setBackground(Color.BLACK);
        label1.setOpaque(true);
        window.add(label1);

        label2 = new JLabel();
        label2.setBounds(532, 0, 266, 800);
        label2.setBackground(Color.RED);
        label2.setOpaque(true);
        window.add(label2);

        keeper = new JButton("Kenneth Vermeer");
        keeper.setBounds(10, 50, 82, 82);
        label.add(keeper);


    }
}

我的音乐课代码:

package music;

import java.io.*;
import javax.sound.sampled.*;

import Controller.HomeController;
import View.Home;

public class PlaySound
{

    {
        sound = new File("../Ajax/src/sound/Sound.wav"); // Write you own file location here and be aware that it need to be an .wav file

        new Thread(play).start();
    }

    static File sound;
    static boolean muted = false; // This should explain itself
    static float volume = 100.0f; // This is the volume that goes from 0 to 100
    static float pan = 0.0f; // The balance between the speakers 0 is both sides and it goes from -1 to 1

    static double seconds = 0.0d; // The amount of seconds to wait before the sound starts playing

    static boolean looped_forever = false; // It will keep looping forever if this is true

    static int loop_times = 0; // Set the amount of extra times you want the sound to loop (you don't need to have looped_forever set to true)
    static int loops_done = 0; // When the program is running this is counting the times the sound has looped so it knows when to stop

    final static Runnable play = new Runnable() // This Thread/Runnabe is for playing the sound
    {
        public void run()
        {    
            try
            {
                // Check if the audio file is a .wav file
                if (sound.getName().toLowerCase().contains(".wav"))
                {
                    AudioInputStream stream = AudioSystem.getAudioInputStream(sound);

                    AudioFormat format = stream.getFormat();

                    if (format.getEncoding() != AudioFormat.Encoding.PCM_SIGNED)
                    {
                        format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,
                                format.getSampleRate(),
                                format.getSampleSizeInBits() * 2,
                                format.getChannels(),
                                format.getFrameSize() * 2,
                                format.getFrameRate(),
                                true);

                        stream = AudioSystem.getAudioInputStream(format, stream);
                    }

                    SourceDataLine.Info info = new DataLine.Info(
                            SourceDataLine.class,
                            stream.getFormat(),
                            (int) (stream.getFrameLength() * format.getFrameSize()));

                    SourceDataLine line = (SourceDataLine) AudioSystem.getLine(info);
                    line.open(stream.getFormat());
                    line.start();

                    // Set Volume
                    FloatControl volume_control = (FloatControl) line.getControl(FloatControl.Type.MASTER_GAIN);
                    volume_control.setValue((float) (Math.log(volume / 100.0f) / Math.log(10.0f) * 20.0f));

                    // Mute
                    BooleanControl mute_control = (BooleanControl) line.getControl(BooleanControl.Type.MUTE);
                    mute_control.setValue(muted);

                    FloatControl pan_control = (FloatControl) line.getControl(FloatControl.Type.PAN);
                    pan_control.setValue(pan);

                    long last_update = System.currentTimeMillis();
                    double since_last_update = (System.currentTimeMillis() - last_update) / 1000.0d;

                    // Wait the amount of seconds set before continuing
                    while (since_last_update < seconds)
                    {
                        since_last_update = (System.currentTimeMillis() - last_update) / 1000.0d;
                    }

                    System.out.println("Playing!");

                    int num_read = 0;
                    byte[] buf = new byte[line.getBufferSize()];

                    while ((num_read = stream.read(buf, 0, buf.length)) >= 0)
                    {
                        int offset = 0;

                        while (offset < num_read)
                        {
                            offset += line.write(buf, offset, num_read - offset);
                        }
                    }


                    line.drain();
                    line.stop();

                    if (looped_forever)
                    {
                        new Thread(play).start();
                    }
                    else if (loops_done < loop_times)
                    {
                        loops_done++;
                        new Thread(play).start();
                    }
                }
            }
            catch (Exception ex) { ex.printStackTrace(); }
        }
    };
}

我的按钮点击类的代码:

package Controller;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import music.PlaySound;

import View.Home;
import View.Selectie;

public class HomeController implements ActionListener {

    private Home home;


    public HomeController(Home home){
        this.home = home;


    }


    public void actionPerformed (ActionEvent e){
            home.dispose();

            Selectie selectie = new Selectie();
            selectie.setVisible(true);

    }
 }

最佳答案

您可以在打开新帧之前在 PlaySound 中设置一个变量来指示播放应该停止。

static boolean shouldStop = false;

static void stopPlayback() {
    shouldStop = true;
}

在 PlaySound 的内部循环中,您退出循环并且线程终止。

while ((num_read = stream.read(buf, 0, buf.length)) >= 0) {
    if ( shouldStop ) {
        break;
    }
   ...
}

关于java - 打开新 JFrame 时停止音乐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9682146/

相关文章:

java - 在 Java 中读取 MIDI 文件

android - 产生特定的音调并继续播放直到停止按钮

java - 如何在 Java 中获取数组中所有持续时间的总和?

java - 如何在 Android 中使用横线/水平线对齐 EditText 中的文本?

java - 如何通过修改 Netbeans 中的父级来影响所有子级?

java - 如何在 jformattedtextfield 中仅添加 double 值

java - 为什么 java AudioSystem.getTargetEncodings( AudioFormat ) 返回的 Encoding 与我们提供的 AudioFormat 的编码不同?

java - Spring Bean 战略模式

java - 二维数组从一个角到另一个角的最小路径

Java Swing : GUI frozen - jstack interpretation