简体   繁体   中英

How to play a background music when the program run? in java

I am making a card game, and it's almost done. The last thing I want to do is play some background music. Now if I copy the file into the default package and make a single jar file of the game, will the music play on all computers? Currently, on my PC it's running without any problem by giving a specific path for the file like "C:\\\\samp.wav"; . But I am worried that if I make a jar file and run it on another PC it won't work properly. I think there will be a FileNotFoundException . Am I right or wrong?

For the card's image I am using this line:

jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/1.jpg")));

Those pictures I have inserted into my default package. I want to do the same for the music file, but how? I am using NetBeans.

You should include the wav file inside your application jar. This way you won't have to manage the copy of the file in the user's file system (keep in mind that, for example, in UNIX, Mac, etc. you can't access to the hard drive through C:/... ).

For example, if you place the wav file in the root of the app jar ( app.jar/samp.wav ):

InputStream is = getClass().getClassLoader().getResourceAsStream("samp.wav");

or, if you had a "sounds" directory in the app jar root ( app.jar/sounds/samp.wav ):

InputStream is = getClass().getClassLoader().getResourceAsStream("sounds/samp.wav");

Check this post for extra information about playing wav files with Java (though for your question, I think you have already solved this problem). Consider as well playing it in a separate thread. Check also this web for examples about managing media files in Java.

import javax.swing.*;
import sun.audio.*;
import java.awt.event.*;
import java.io.*;
public class Sound {
public static void main(String[] args)
{
JFrame frame = new JFrame();
frame.setSize(200,200);
JButton button = new JButton("Click me");
frame.add(button);
button.addActionListener(new AL());
frame.setVisible(true);
}
public static class AL implements ActionListener{
public final void actionPerformed(ActionEvent e){
music();
}
}
public static void music(){
AudioPlayer MGP = AudioPlayer.player;
AudioStream BGM;
AudioData MD;
ContinuousAudioDataStream loop = null;
try{
BGM = new AudioStream(new FileInputStream("C:\\test\\ha.wav"));
MD = BGM.getData();
loop = new ContinuousAudioDataStream(MD);
}catch(IOException error){
System.out.print("file not found");
}
MGP.start(loop);
}
}

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