Java 在JFrame窗口的背景中播放音乐

Java 在JFrame窗口的背景中播放音乐,java,audio,jframe,audio-streaming,Java,Audio,Jframe,Audio Streaming,我试图在一个框架窗口的背景中播放一个音频文件,我发现它比仅仅添加一张图片要复杂得多 我找到了一个“教程”,应该知道如何添加音乐,它看起来相当简单,至少在所需的代码量上是如此。但是,我不能播放音频文件,它说了两件事 第一个-我试图播放一个复制到java项目中的音频文件,这告诉我它找不到该文件或目录 我给了这个方法一个音频文件的路径,它告诉我 could not get audio input stream from input file 请记住,我是一个新手,本教程没有提供太多帮助,所以我不知道

我试图在一个框架窗口的背景中播放一个音频文件,我发现它比仅仅添加一张图片要复杂得多

我找到了一个“教程”,应该知道如何添加音乐,它看起来相当简单,至少在所需的代码量上是如此。但是,我不能播放音频文件,它说了两件事

第一个-我试图播放一个复制到java项目中的音频文件,这告诉我它找不到该文件或目录

我给了这个方法一个音频文件的路径,它告诉我

could not get audio input stream from input file
请记住,我是一个新手,本教程没有提供太多帮助,所以我不知道这个游戏方法到底在做什么。我很想学习如何做到这一点,但我所看到的一切对于这个项目来说都过于复杂,我没有时间投入,因为没有必要,只是增加了一点天赋而已

非常感谢您的帮助!!我在有问题的代码周围加了星星

public MultiForm() {
    super("Multi Form Program");        
    setLayout(new FlowLayout());
    menu = new JComboBox(fileName);
    add(menu);

    /*How to add a background image to the Menu.
     * add(new JLabel(new ImageIcon(getClass().getResource("MatrixPIC.png"))));
     */

    TheHandler handler = new TheHandler();
    menu.addItemListener(handler);  
}

public void matrixPanel() {

    TheHandler handler = new TheHandler();
    //Create a new window when "The Matrix" is clicked in the JCB
    newFrame = new JFrame();
    panel = new JPanel();
    panel2 = new JPanel();

    newFrame.setLayout(new FlowLayout());
    newFrame.setSize(500, 300);
    newFrame.setDefaultCloseOperation(newFrame.EXIT_ON_CLOSE);      

    matrixQuote = new JLabel("<html><center>After this, there is no turning back. "
            + "<br><center>You take the blue pill—the story ends, you wake up "
            + "<br><center>in your bed and believe whatever you want to believe."
            + "<br><center>You take the red pill—you stay in Wonderland, and I show"
            + "<br><center>you how deep the rabbit hole goes. "
            + "<br><center>Remember: all I'm offering is the truth. Nothing more.</html>");

    panel.add(matrixQuote);
    newFrame.add(panel, BorderLayout.NORTH);

    //Blue pill button and picture. 
    Icon bp = new ImageIcon(getClass().getResource("Blue Pill.png"));
    bluePill = new JButton("Blue Pill", bp);
    panel2.add(bluePill);   
    bluePill.addActionListener(handler);

    //Red pill button and picture
    Icon rp = new ImageIcon(getClass().getResource("Red Pill.png"));
    redPill = new JButton("Red Pill", rp);
    panel2.add(redPill);

    newFrame.add(panel2, BorderLayout.CENTER);      
    newFrame.setVisible(true);
}

*********************************************************************************
public void play(String path, int delay, int numberOfLoops) {
    for(int i = 0; i < numberOfLoops; i++) {
        new Thread() {
            @Override
            public void run() {
                try {
                    File file = new File(path);
                    Clip clip = AudioSystem.getClip();
                    clip.open(AudioSystem.getAudioInputStream(file));
                    clip.start();
                    Thread.sleep(clip.getMicrosecondLength());

                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
            }
        }.start();
        try {
            Thread.sleep(delay);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
*********************************************************************************        

private class TheHandler implements ItemListener, ActionListener{

    public void itemStateChanged(ItemEvent IE) {
        //listen for an item to be selected.
        if(IE.getStateChange() == ItemEvent.SELECTED) {
            Object selection = menu.getSelectedItem();

            if("The Matrix".equals(selection)) {
                matrixPanel();
            }
            else if("Another Option".equals(selection)) {   
            }
        }   
    }


    public void actionPerformed(ActionEvent AE) {
        if(AE.getSource() == bluePill) {
            //Clear panels after button is clicked.
            newFrame.remove(panel);         
            newFrame.remove(panel2);
            newFrame.repaint();
    *********************************************************************************       
            play("/Users/SWD/Downloads/fail.mp3", 10, 30);
 *********************************************************************************  
            newFrame.setSize(600, 400);
            bpPanelLabel = new JPanel();
            bpLabel = new JLabel("<html><center>WELCOME TO THE BEGINING OF YOUR NEW LIFE!  " +
                     "<br><center>YOU'RE ABOUT TO SEE HOW DEEP THE RABBIT HOLE GOES!</html>");
            newFrame.add(bpLabel);
            newFrame.add(bpPanelLabel, BorderLayout.NORTH);
            bpPanelPic = new JPanel();
            newFrame.add(new JLabel(new ImageIcon(getClass().getResource("MatrixPIC.png"))));
            newFrame.add(bpPanelPic, BorderLayout.CENTER);  
            newFrame.validate();
        }


    }   
}


//Main method sets up the main JFrame with the menu
public static void main(String[] args) {

    MultiForm go = new MultiForm();
    go.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    go.setSize(400, 200);
    go.setVisible(true);
}
}
public MultiForm(){
超级(“多形式程序”);
setLayout(新的FlowLayout());
菜单=新的JComboBox(文件名);
添加(菜单);
/*如何将背景图像添加到菜单中。
*添加(新的JLabel(新的图像图标(getClass().getResource(“MatrixPIC.png”)));
*/
TheHandler=新的TheHandler();
addItemListener(处理程序);
}
公共无效matrixPanel(){
TheHandler=新的TheHandler();
//在JCB中单击“矩阵”时创建一个新窗口
newFrame=newjframe();
panel=新的JPanel();
panel2=新的JPanel();
setLayout(newflowLayout());
新帧设置大小(500300);
newFrame.setDefaultCloseOperation(newFrame.EXIT_ON_CLOSE);
matrixQuote=new JLabel(“在此之后,就没有回头路了。”
+
你吃了蓝色药丸故事结束后,你醒了 +“躺在床上,相信你想相信的一切。” +“
你吃了红色药丸,你留在仙境,我给你看” +“你知道兔子洞有多深。” +“
记住:我所提供的只是真相,没有更多。”); 面板。添加(矩阵报价); 添加(面板,边框布局,北); //蓝色药丸按钮和图片。 Icon bp=新的图像图标(getClass().getResource(“Blue Pill.png”); 蓝色药丸=新的JButton(“蓝色药丸”,bp); 第2组:添加(蓝丸); bluePill.addActionListener(处理程序); //红色药丸按钮和图片 Icon rp=新的图像图标(getClass().getResource(“Red Pill.png”); 红色药丸=新的JButton(“红色药丸”,rp); 第2组。添加(红色药丸); 添加(panel2,BorderLayout.CENTER); newFrame.setVisible(true); } ********************************************************************************* 公共无效播放(字符串路径、整数延迟、整数循环){ for(int i=0;i你就要看到兔子洞有多深了!”; newFrame.add(bpLabel); 添加(bpPanelLabel,BorderLayout.NORTH); bpPanelPic=新的JPanel(); 添加(新的JLabel(新的图像图标(getClass().getResource(“MatrixPIC.png”))); 添加(bpPanelPic,BorderLayout.CENTER); newFrame.validate(); } } } //Main方法使用菜单设置主框架 公共静态void main(字符串[]args){ 多形式go=新的多形式(); go.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 设置大小(400200); go.setVisible(true); } }
  • Java的音频API不支持(全部)mp3编码。如果你需要播放mp3,那么你应该看看
  • 如果您试图播放的文件在项目的src(或扩展名为Jar的文件)中,则需要使用
    Class#getResource
    Class#getResourceAsStream
  • Clip
    auto本身支持循环,因此您不需要使用自己的循环,这可能会阻止事件调度线程
  • 线程
    import java.awt.EventQueue;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.File;
    import java.io.IOException;
    import javax.sound.sampled.AudioSystem;
    import javax.sound.sampled.Clip;
    import javax.sound.sampled.LineUnavailableException;
    import javax.sound.sampled.UnsupportedAudioFileException;
    import javax.swing.JButton;
    import javax.swing.JFileChooser;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JSpinner;
    import javax.swing.JTextField;
    import javax.swing.SpinnerNumberModel;
    import javax.swing.Timer;
    import javax.swing.UIManager;
    import javax.swing.UnsupportedLookAndFeelException;
    import javax.swing.filechooser.FileFilter;
    
    public class JavaApplication5 {
    
        public static void main(String[] args) {
            new JavaApplication5();
        }
    
        public JavaApplication5() {
            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    try {
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                        ex.printStackTrace();
                    }
    
                    JFrame frame = new JFrame("Testing");
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.add(new TestPane());
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                }
            });
        }
    
        public class TestPane extends JPanel {
    
            private Clip clip = null;
    
            private JTextField audioFile;
            private JButton browse;
            private JSpinner loops;
            private JSpinner delay;
            private JFileChooser chooser;
    
            public TestPane() {
                setLayout(new GridBagLayout());
                GridBagConstraints gbc = new GridBagConstraints();
                gbc.gridx = 0;
                gbc.gridy = 0;
                add(new JLabel("Audio File:"), gbc);
    
                gbc.gridwidth = GridBagConstraints.REMAINDER;
                gbc.weightx = 1;
                gbc.gridx++;
                gbc.fill = GridBagConstraints.HORIZONTAL;
                gbc.anchor = GridBagConstraints.WEST;
                audioFile = new JTextField(20);
                add(audioFile);
    
                gbc.gridwidth = 1;
                gbc.weightx = 0;
                gbc.gridx++;
                browse = new JButton("...");
                add(browse, gbc);
    
                gbc.gridx = 0;
                gbc.gridy++;
                add(new JLabel("Loops: "), gbc);
    
                loops = new JSpinner(new SpinnerNumberModel(1, 1, 100, 1));
                gbc.gridx++;
                gbc.fill = GridBagConstraints.NONE;
                add(loops, gbc);
    
                gbc.gridx = 0;
                gbc.gridy++;
                add(new JLabel("Delay (seconds): "), gbc);
    
                delay = new JSpinner(new SpinnerNumberModel(0, 0, 10, 1));
                gbc.gridx++;
                gbc.fill = GridBagConstraints.NONE;
                add(delay, gbc);
    
                gbc.anchor = GridBagConstraints.CENTER;
                gbc.gridx = 0;
                gbc.gridy++;
                gbc.gridwidth = GridBagConstraints.REMAINDER;
                JButton play = new JButton("Play");
                add(play, gbc);
    
                play.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        try {
                            play(
                                            audioFile.getText(),
                                            (int) delay.getValue(),
                                            (int) loops.getValue());
                        } catch (LineUnavailableException | IOException | UnsupportedAudioFileException ex) {
                            ex.printStackTrace();;
                            JOptionPane.showMessageDialog(TestPane.this, "<html>Failed to play audio file:</br>" + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
                        }
                    }
                });
    
                browse.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        if (chooser == null) {
                            chooser = new JFileChooser();
                            chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
                            chooser.setMultiSelectionEnabled(false);
                            chooser.addChoosableFileFilter(new FileFilter() {
                                @Override
                                public boolean accept(File f) {
                                    System.out.println(f);
                                    return f.getName().toLowerCase().endsWith(".wav");
                                }
    
                                @Override
                                public String getDescription() {
                                    return "Wave Files (.wav)";
                                }
                            });
                        }
    
                        if (chooser.showOpenDialog(TestPane.this) == JFileChooser.APPROVE_OPTION) {
                            File selected = chooser.getSelectedFile();
                            audioFile.setText(selected.getPath());
                        }
                    }
                });
    
            }
    
            public void play(String path, int delay, int numberOfLoops) throws LineUnavailableException, IOException, UnsupportedAudioFileException {
                if (clip != null) {
                    clip.stop();
                    clip = null;
                }
    
                if (delay > 0) {
                    System.out.println("Start with delay");
                    Timer timer = new Timer(delay * 1000, new ActionListener() {
                        @Override
                        public void actionPerformed(ActionEvent e) {
                            try {
                                play(path, numberOfLoops);
                            } catch (UnsupportedAudioFileException | LineUnavailableException | IOException ex) {
                                ex.printStackTrace();;
                                JOptionPane.showMessageDialog(TestPane.this, "<html>Failed to play audio file:</br>" + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
                            }
                        }
                    });
                    timer.setRepeats(false);
                    timer.start();
                } else {
                    play(path, numberOfLoops);
                }
            }
    
            private void play(String path, int numberOfLoops) throws UnsupportedAudioFileException, LineUnavailableException, IOException {
                File file = new File(path);
                if (file.exists()) {
                    clip = AudioSystem.getClip();
                    clip.open(AudioSystem.getAudioInputStream(file));
                    clip.start();
                }
            }
        }
    
    }