如何在可运行的jar文件中运行音乐?编译和运行代码时,我的程序运行音乐。但是当我尝试通过eclipse将其变成一个可运行的jar文件时,由于某种原因它不会运行音乐。
我的代码
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.LineBorder;
import sun.audio.*;
import java.io.*;
public class Birthday {
static JFrame bDay = new JFrame();
static JPanel panel = new JPanel(null);
public static void main(String[] args) {
fillPanel();
bDay.add(panel);
panel.setFocusable(true);
bDay.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);/
bDay.setSize(325,250);
bDay.setLocationRelativeTo(null);
bDay.setTitle("Happy Birthday");
bDay.setResizable(true);
bDay.setVisible(true);
}
public static void fillPanel(){
Color fav = new Color(50,190, 189);
fav = generatePastelColor(fav);
panel.setBackground(fav);
JLabel hb = new JLabel("HAPPY BIRTHDAY!!");
hb.setFont(new Font("Verdana", 2,30));
hb.setBorder(new LineBorder(Color.WHITE));
panel.add(hb);
hb.setBounds(8, 50, 295, 50);
JButton button = new JButton("Click me");
panel.add(button);
button.setBounds(50, 150, 200, 50);
button.addActionListener(new AL());
}
public static class AL implements ActionListener{
public final void actionPerformed(ActionEvent e){
music();
}
}
public static Color generatePastelColor(Color mix) {
int red = 50;
int green = 190;
int blue = 189;
// mix the color
if (mix != null) {
red = (red + mix.getRed()) / 2;
green = (green + mix.getGreen()) / 2;
blue = (blue + mix.getBlue()) / 2;
}
Color color = new Color(red, green, blue);
return color;
}
public static void music(){
AudioPlayer mgp = AudioPlayer.player;
AudioStream bgm;
AudioData md;
ContinuousAudioDataStream loop = null;
try {
bgm = new AudioStream(new FileInputStream(new File("music\\Birthday.wav")));
md = bgm.getData();
loop = new ContinuousAudioDataStream(md);
} catch (IOException e) {
e.printStackTrace();
}
mgp.start(loop);
}
}
答案 0 :(得分:3)
Jar文件中的文件不再是文件,因此将其更改为将其作为资源读取
bgm = new AudioStream(new FileInputStream(new File("music\\Birthday.wav")));
到
bgm = new AudioStream(Birthday.class.getResourceAsStream ("/music/Birthday.wav"));
假设您在classpath的根目录中有music/Birthday.wav