-2

我正在尝试将背景音乐添加到我的程序中,但是当我指定音频文件的路径时,我收到了错误消息。我怎么能指定这个(这将被发送给另一个人)。所以路径不能在我的系统上,它也必须位于 JAR 中。

package main;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

javax.sound.sampled.AudioSystem;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

import sun.audio.AudioPlayer;
import sun.audio.AudioStream;

public class Main extends JFrame {
/**
 * 
 */
private static final long serialVersionUID = 1L;
private JPanel contentPane;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                Main frame = new Main();
                frame.setVisible(true);
                PlaySound();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 */
public static void PlaySound() {
    InputStream in;
    try {
        in = new FileInputStream(new File("/audio/Happy_Happy_Birthday.wav"));
        AudioStream audios = new AudioStream(in);
        AudioPlayer.player.start(audios);
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, e);

    }

}

public Main() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 717, 508);
    contentPane = new JPanel() {
        /**
         * 
         */
        private static final long serialVersionUID = 1L;

        public void paintComponent(Graphics g) {
            Image img = Toolkit.getDefaultToolkit().getImage(
                    Main.class.getResource("/images/happy_birthday.jpg"));
            g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), this);
        }
    };
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    contentPane.setLayout(new BorderLayout(0, 0));
    setContentPane(contentPane);
}
}
4

2 回答 2

2
  • 使用 aURL而不是 a加载剪辑File。到部署时,这些资源可能会变成一个。在这种情况下,资源必须由URL而不是访问File。请参阅标签的信息页面,了解形成URL.
  • 使用 a 播放声音javax.sound.sampled.Clip(与sun.audio包中未记录的类相反)。请参阅Java 声音信息。工作源页面
于 2013-08-31T22:25:47.930 回答
-1
InputStream in;
    try {
        in = new FileInputStream(new File("Jock_Jams_-_Are_You_Ready_For_This.wav"));
        AudioStream audios = new AudioStream(in);
        AudioPlayer.player.start(audios);
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, e);

    }

我在我的 while 循环之外使用它,只要你不介意它无法停止它就可以工作。

于 2016-09-09T12:46:43.253 回答