简体   繁体   中英

How to run music in runnable jar file

How would I be able to run music in a runnable jar file? My programs runs the music when I compile and run the code. But when I try making it into a runnable jar file through eclipse, it does not run the music for some reason.

My code

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);
 }
}

File inside Jar file is no longer a File, so change it to read it as resource

bgm = new AudioStream(new FileInputStream(new File("music\\Birthday.wav")));

to

bgm = new AudioStream(Birthday.class.getResourceAsStream ("/music/Birthday.wav"));

assuming you have music/Birthday.wav at the root of classpath

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM