How to play a background music when the program run? in java(程序运行时如何播放背景音乐?在java中)
问题描述
我正在制作一款纸牌游戏,并且快完成了.我想做的最后一件事是播放一些背景音乐.现在如果我将文件复制到默认包中并制作一个游戏的jar文件,音乐会在所有计算机上播放吗?目前,在我的 PC 上,通过为文件提供特定路径(如 "C:\samp.wav";
),它可以毫无问题地运行.但我担心如果我制作一个 jar 文件并在另一台 PC 上运行它,它将无法正常工作.我想会有一个FileNotFoundException
.我是对还是错?
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")));
我已经插入到我的默认包中的那些图片.我想对音乐文件做同样的事情,但是怎么做呢?我正在使用 NetBeans.
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.
推荐答案
您应该在应用程序 jar 中包含 wav 文件.这样您就不必管理用户文件系统中的文件副本(请记住,例如,在 UNIX、Mac 等中,您无法通过 C 访问硬盘驱动器:/...
).
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:/...
).
例如,如果您将 wav 文件放在 app jar 的根目录中(app.jar/samp.wav
):
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");
或者,如果您在应用 jar 根目录中有声音"目录 (app.jar/sounds/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");
查看这篇文章了解更多关于使用 wav 文件播放的信息Java(尽管对于您的问题,我认为您已经解决了这个问题).考虑在单独的线程中播放它.另请查看此网站以获取有关使用 Java 管理媒体文件的示例.
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.
这篇关于程序运行时如何播放背景音乐?在java中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:程序运行时如何播放背景音乐?在java中


基础教程推荐
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 降序排序:Java Map 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01