在我的主屏幕上播放音乐

时间:2012-03-06 14:00:25

标签: java eclipse swing javasound audio

我正在使用背景音乐构建应用程序。 我写了一堂课来播放音乐,当我运行它时它会开始播放。 我还写了一个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.io.File;


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

import javax.swing.JPanel;

import music.PlaySound;

public class Home extends JFrame {

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

    public Home (){
        initGUI();
    }

    public void initGUI(){
        setLayout(null);
        setTitle("Ismail");
        setPreferredSize(new Dimension(800,600));
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

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

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

        label2 = new JLabel("AFCA2");
        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, 100, 188, 188);
        label1.add(logo);

        pack();
    }

}

我的声音课程代码:

package music;

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

public class PlaySound
{
    public static void main(String[] args)
    {
        sound = new File("../Ajax/src/sound/Sound.wav"); // Write you own file location here and be aware that it needs 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(); }
        }
    };
}

1 个答案:

答案 0 :(得分:0)

听起来你需要在你的JFrame中添加一个WindowListener。像这样:

public Home() {
    initGUI();
    this.addWindowListener(new WindowAdapter() {
        @Override
        public void windowOpened(WindowEvent e) {
            PlaySound.sound = new File("../Ajax/src/sound/Sound.wav");
            soundThread = new Thread(PlaySound.play).start();
        }
        //If you want the sound to stop you can just add another override, but you need to keep track of the sound thread
        @Override
        public void windowClosing(WindowEvent e) {
            soundThread.interrupt();
        }
    });
}