Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
706 views
in Technique[技术] by (71.8m points)

audio - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...