【发布时间】:2014-01-18 23:14:26
【问题描述】:
所以我的应用程序应该在我每次点击面板时播放 WAV 文件。但现在的问题是,它要等待第一个完成,然后再播放第二个。我希望能够让它们同时播放。
我放 Thread.sleep(500) 的原因是因为如果我不放,那么它根本不会播放声音:(
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.FloatControl;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.swing.JFrame;
@SuppressWarnings("serial")
public class SoundEffectPlayer extends JFrame {
/*
* Jframe stuff
*/
public SoundEffectPlayer() {
this.setSize(400, 400);
this.setTitle("Mouse Clicker");
this.addMouseListener(new Clicker());
this.setVisible(true);
}
private class Clicker extends MouseAdapter {
public void mouseClicked(MouseEvent e) {
try {
playSound(1);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
/*
* Directory of your sound files
* format is WAV
*/
private static final String DIRECTORY = "file:///C:/Users/Jessica/Desktop/audio/effects/sound 1.wav";
/*
* The volume for sound effects
*/
public static float soundEffectsVolume = 0.00f;
/*
* Loads the sound effect files from cache
* into the soundEffects array.
*/
public void playSound(int ID) throws InterruptedException {
try {
System.out.println("playing");
Clip clip;
URL url = new URL(DIRECTORY);
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(url);
clip = AudioSystem.getClip();
clip.open(audioInputStream);
clip.setFramePosition(0);
FloatControl gainControl = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN);
gainControl.setValue(soundEffectsVolume);
clip.start();
System.out.println("played");
Thread.sleep(3000);
System.out.println("closing");
} catch (MalformedURLException e) {
System.out.println("Sound effect not found: "+ID);
e.printStackTrace();
return;
} catch (UnsupportedAudioFileException e) {
System.out.println("Unsupported format for sound: "+ID);
return;
} catch (LineUnavailableException e) {
e.printStackTrace();
return;
} catch (IOException e) {
e.printStackTrace();
return;
}
}
public static void main(String[] args) throws InterruptedException {
new SoundEffectPlayer();
}
}
更新:好的,所以我让它们同时播放,但我想在 Clip 播放完毕后关闭线程,而不是让线程等待 500 毫秒
我该怎么做?
【问题讨论】:
-
看起来您正在事件调度线程上播放音频,这基本上会冻结应用程序,直到音频完成。是这样吗?您可能想创建一个新线程来播放音频。你知道怎么做吗?
-
不,我是线程新手:c
-
我看到你是intending to ignore me。请注意,可以双向..
-
对不起,安德鲁,我的帖子冒犯了你,我没有回复,因为帖子被锁定了,我意识到这里不允许人们回答这个问题:|