Java中的声音问题 [英] Sound problems in Java
问题描述
我对使用Java播放声音有一些疑问,我希望你能帮助我。
1.如何使用停止按钮停止播放声音?
2.如何减慢(或冷却时间)声音?
3.我想创建一个可以调节音量和静音选项的选项框架,我该怎么做?
这是我的代码:
I have some questions about playing sound in Java and I hope you can help me out.
1. How can I stop a playing sound with a "Stop" button?
2. How can I slow down (or cooldown time) a sound?
3. I want to create a option frame where I can adjust volume and have mute option, how can I do that?
This is my code:
private void BGM() {
try {
File file = new File(AppPath + "\\src\\BGM.wav");
Clip clip = AudioSystem.getClip();
clip.open(AudioSystem.getAudioInputStream(file));
clip.start();
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
任何帮助将不胜感激,并且,有一个美好的一天!
Any help will be greatly appreciated, and, Have a nice day!
推荐答案
您正在使用面向对象的编程语言,所以让我们利用它并封装管理剪辑/音频变成一个简单的类......
You're working in an Object Oriented programming lanuage, so let's take advantage of that and encapsulate the management of the clip/audio into a simple class...
public class AudioPlayer {
private Clip clip;
public AudioPlayer(URL url) throws IOException, LineUnavailableException, UnsupportedAudioFileException {
clip = AudioSystem.getClip();
clip.open(AudioSystem.getAudioInputStream(url.openStream()));
}
public boolean isPlaying() {
return clip != null && clip.isRunning();
}
public void play() {
if (clip != null && !clip.isRunning()) {
clip.start();
}
}
public void stop() {
if (clip != null && clip.isRunning()) {
clip.stop();
}
}
public void dispose() {
try {
clip.close();
} finally {
clip = null;
}
}
}
现在,要使用它,你需要创建一个类实例字段,它允许你从你想要使用它的类中的任何地方访问它...
Now, to use it, you need to create a class instance field which will allow you to access the value from anywhere within the class you want to use it...
private AudioPlayer bgmPlayer;
然后,当你需要它时,你创建一个 AudioPlayer的实例
并将其分配给此变量
Then, when you need it, you create an instance of AudioPlayer
and assign it to this variable
try {
bgmPlayer = new AudioPlayer(getClass().getResource("/BGM.wav"));
} catch (IOException | LineUnavailableException | UnsupportedAudioFileException ex) {
ex.printStackTrace();
}
现在,当您需要时,只需拨打 bgmPlayer.play()
或 bgmPlayer.stop()
Now, when you need to, you simply call bgmPlayer.play()
or bgmPlayer.stop()
这篇关于Java中的声音问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!