我对使用Java播放声音有一些疑问,希望你能帮帮我
1.如何通过" Stop"停止播放声音?按钮?
2.如何减慢(或冷却时间)声音?
3.我想创建一个选项框架,我可以调整音量和静音选项,我该怎么做?
这是我的代码:
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());
}
}
任何帮助将不胜感激,并祝你有愉快的一天!
答案 0 :(得分:1)
您正在使用面向对象的编程语言,所以让我们利用它并将剪辑/音频的管理封装到一个简单的类中......
System.setProperty("javax.net.ssl.trustStore", trustStorePath);//The path to the trust store file
System.setProperty("javax.net.ssl.trustStorePassword", trustStorePassword);//The trust store password
try(SSLServerSocket socket = (SSLServerSocket) SSLServerSocketFactory.getDefault().createServerSocket(ssl_listen_port)) {
socket.setReuseAddress(true);
System.out.println("\tServer SSL socket created on port " + ssl_listen_port);
while(serverActive) {
//Omitted multithreading code for read-ability:
final SSLSocket s = (SSLSocket) socket.accept();
try {
s.startHandshake();
} catch(SSLHandshakeException e) {
System.err.println("Failed to initialize SSL handshake: " + e.getMessage());
continue;
}
//(The server then handles the remainder of the request as if it were http.)
}
} catch(BindException e) {
System.err.println(" /!\\\tUnable to bind to ssl port " + ssl_listen_port + ":\r\n/___\\\t" + e.getMessage());
} catch(Throwable e) {
e.printStackTrace();
}
现在,要使用它,您需要创建一个类实例字段,它允许您从要使用它的类中的任何位置访问该值...
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;
}
}
}
然后,当您需要它时,您创建一个private AudioPlayer bgmPlayer;
的实例并将其分配给此变量
AudioPlayer
现在,您需要时,只需拨打try {
bgmPlayer = new AudioPlayer(getClass().getResource("/BGM.wav"));
} catch (IOException | LineUnavailableException | UnsupportedAudioFileException ex) {
ex.printStackTrace();
}
或bgmPlayer.play()