I am attempting to add background music to my program but when i specify the path to the audio file i get the error message. How else can I specify this(this is going to be sent to another person). So the path cannot be on my system, it must be located in the JAR as well.
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);
}
}
URL
rather than aFile
. By the time of deployment, those resources will likely become an embedded-resource. That being the case, the resource must be accessed byURL
instead ofFile
. See the info page for the tag, for a way to form anURL
.javax.sound.sampled.Clip
(as opposed to undocumented classes in thesun.audio
package). See the Java Sound info. page for working source.