void playInstrumentSound(InstrumentModel instrument) {
if (instrument.getMedia() != null) {
new Thread() {
public void run() {
instrument.setPlaying(true);
MediaPlayer player = new MediaPlayer(instrument.getMedia());
player.setVolume(1);
player.play();
try {
Thread.sleep(properties.getSleepLength());
} catch (InterruptedException e) {
e.printStackTrace();
}
instrument.setPlaying(false);
player.dispose();
}
}.start();
}
}
InstrumentModel是我的类,其中包含通过使用pathToSound初始化的媒体对象,pathToSound是资源文件夹中.wav文件的路径:
if (this.pathToSound != null) {
media = new Media(new File(this.pathToSound).toURI().toString());
}
例如,如果.wav文件的持续时间是300ms线程睡眠(300)在playeinstrumentSound()方法中,我可以听到完整的声音,但在这300毫秒内我不能播放不同的声音线程睡眠(50)然后我几乎可以立即再点击它,但我只听到50毫秒的.wav文件。
编辑:
我只是想换一种方法:
void playInstrumentSound(InstrumentModel instrument) {
if (instrument.getMedia() != null) {
instrument.setPlaying(true);
MediaPlayer player = new MediaPlayer(instrument.getMedia());
player.setVolume(1);
player.play();
new Thread() {
public void run() {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
instrument.setPlaying(false);
}
}.start();
new Thread() {
public void run() {
try {
Thread.sleep(250);
} catch (InterruptedException e) {
e.printStackTrace();
}
player.dispose();
}
}.start();
}
现在,它应该在250毫秒后关闭声音,并在50毫秒后更改isPlaying标志(如果isPlaying flag为真,则不能再次敲击鼓)。你觉得这可能有用吗?