Java 应用程序如何播放声音片段?
以下是我见过的最有可能的解释的链接,但我仍然有疑问。
我'我将在此处引用代码:
public static synchronized void playSound(final String url) {
new Thread(new Runnable() {
public void run() {
try {
Clip clip = AudioSystem.getClip();
AudioInputStream inputStream = AudioSystem.getAudioInputStream(Main.class.getResourceAsStream("/path/to/sounds/" + url));
clip.open(inputStream);
clip.start();
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}).start();
}
- 这是否可以在应用程序中工作,而不是在 Applet 中?
- 方法 Main.class.getResourceAsStream() 似乎需要 import com.sun.tools.apt.Main; 但我找不到相关文档,而且我不知道它的作用。例如,“/path/to/sounds/”是绝对的还是相对的,如果是后者,相对于哪里?
我现在花了很多时间尝试播放简单的音效。令人难以置信的是,这是多么困难。我希望上面的代码能够工作。感谢您的任何帮助。
章
The following is a link to the most likely explanation I've seen, but I still have questions.
I'll quote the code here:
public static synchronized void playSound(final String url) {
new Thread(new Runnable() {
public void run() {
try {
Clip clip = AudioSystem.getClip();
AudioInputStream inputStream = AudioSystem.getAudioInputStream(Main.class.getResourceAsStream("/path/to/sounds/" + url));
clip.open(inputStream);
clip.start();
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}).start();
}
- Does this work in an application, as opposed to an Applet?
- The method Main.class.getResourceAsStream() seems to require import com.sun.tools.apt.Main; but I cannot find documentation for that, and I don't know what it does. For instance, is "/path/to/sounds/" absolute, or relative, and if the latter, relative to where?
I've spent many hours now trying to play a simple sound effect. It's unbelievable how difficult it is. I hope that the above code can be made to work. Thanks for any help.
Chap
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我总是加载这样的声音:
但您的方法也应该有效。
I always loaded sounds like this:
but your method should also work.
它适用于任何一种。
你从哪里得到这个想法的?我已经做了很多合理的例子,但从未听说过您不应该使用的类。
不,
com.sun
类不仅没有文档记录,而且可能在下一个微版本中发生变化。它相对于类路径的根。
一般来说,媒体处理很棘手。
顺便说一句 - 我对链接线程上的代码印象不深。正如一些评论中提到的,即使同时播放多个 Clip 实例,
Thread
包装器也是不必要的。相反,请参阅 这段代码是我(编写并)个人推荐的。
It works in either.
Where did you get that idea? I've made plenty of sound examples, and never heard of that class that you should not be using.
No, the
com.sun
classes are not only undocumented, but might change in the next micro-version.It is relative to the root of the class-path.
Media handling in general, is tricky.
BTW - I'm not much impressed with the code on the linked thread. The
Thread
wrapper is unnecessary, as mentioned in several of the comments, even for playing multipleClip
instances simultaneously.Instead see this code that I (wrote &) personally recommend.
尽管我大量借鉴了 @Andrew 的代码,但我确实必须在这里或那里进行一些调整。以下是我的解决方案的演示,除了示例 .wav 文件外,该演示已完成。
Although I drew heavily from @Andrew's code, I did have to make some tweaks here and there. The following is a demo of my solution, complete except for a sample .wav file.