我有一个主要发生游戏逻辑的游戏。我刚刚根据我发现的文档添加了声音播放:
//////////////////////SOUND/////////////////////////
SourceDataLine soundLine = null;
int BUFFER_SIZE = 64*1024; // 64 KB
// Set up an audio input stream piped from the sound file.
try {
File soundFile = new File("tim ph3 samplepart1.wav");
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(soundFile);
AudioFormat audioFormat = audioInputStream.getFormat();
DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat);
soundLine = (SourceDataLine) AudioSystem.getLine(info);
soundLine.open(audioFormat);
soundLine.start();
int nBytesRead = 0;
byte[] sampledData = new byte[BUFFER_SIZE];
while (nBytesRead != -1) {
nBytesRead = audioInputStream.read(sampledData, 0, sampledData.length);
if (nBytesRead >= 0) {
// Writes audio data to the mixer via this source data line.
soundLine.write(sampledData, 0, nBytesRead);
}
}
} catch (UnsupportedAudioFileException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} catch (LineUnavailableException ex) {
ex.printStackTrace();
} finally {
soundLine.drain();
soundLine.close();
}
/////////////////////////////////////////////////////
它播放我在 Eclipse 项目文件夹中的文件中指定的文件。
问题?它会阻止所有出现在主体中的游戏逻辑。
这是有道理的——程序是连续的,直到整首歌曲完成……我认为游戏无法继续。
这显然是行不通的,看来我将不得不去可怕的多线程......但在我这样做之前......我想知道......是否有Java库或其他一些聪明的解决方案可以避免在这种情况下多线程?