【发布时间】:2015-03-05 22:19:31
【问题描述】:
我正在开发一款游戏,但我在多次播放相同的声音时遇到了一些问题,就像您激活一个已经在播放的声音一样,它不应该取消第一个声音。我在 Stackoverflow 上找到的解决方案是将其读入字节数组,我采用以下方式:
public SoundObject(AudioInputStream audioIn) {
try {
af = audioIn.getFormat();
size = (int) (af.getFrameSize() * audioIn.getFrameLength());
audio = new byte[size];
info = new DataLine.Info(Clip.class, af, size);
audioIn.read(audio, 0, size);
} catch (IOException e) {
e.printStackTrace();
}
}
public void playSound() {
try {
Clip localSound = (Clip) AudioSystem.getLine(info);
localSound.open(af, audio, 0, size);
localSound.start();
} catch (LineUnavailableException e) {
e.printStackTrace();
}
}
直到现在我试图将它导出到一个 jar 文件中,这一直运行良好,jar 文件由于某种原因在播放字节数组时出现问题,导致声音在几毫秒后被切断,我设法找到了一个发布同样的问题,有人提出了以下解决方案:
public SoundObject(String filePath) {
try {
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(Loader.class.getResource(filePath));
clip = AudioSystem.getClip();
clip.open(audioInputStream);
} catch (IOException e) {
e.printStackTrace();
} catch (LineUnavailableException e) {
e.printStackTrace();
} catch (UnsupportedAudioFileException e) {
e.printStackTrace();
}
}
// Play the sound in a separate thread.
public void playSound() {
Runnable soundPlayer = new Runnable() {
@Override
public void run() {
try {
clip.setMicrosecondPosition(0);
clip.start();
} catch (Exception e) {
e.printStackTrace();
}
}
};
new Thread(soundPlayer).start();
}
使用第二种方法适用于 jar 文件,但问题是声音播放不如以前好,我有一个拍摄功能,如果你拍摄得非常快,这种方法并不总是能接受当我按空格射击时,有时无法播放声音。因此,对于这 2 种解决方案,我必须从不可靠的声音中做出选择,或者我将无法将其导出到可运行的 JAR。
有人遇到过这类问题吗?
编辑:这是一个向您展示 2 个罐子如何工作的剪辑:https://www.youtube.com/watch?v=wZPOIhHZSJM&
【问题讨论】:
标签: audio