我有一个主游戏发生在游戏逻辑。我只是说声音播放按照文件,我发现:多线程只能用Java播放背景音乐吗?
//////////////////////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库或其他在这种情况下避免多线程的巧妙解决方案?
多线程并不是所有这些令人害怕的东西。我记得在学习之前也有同样的感觉,但它非常合乎逻辑。调试线程间某些共享资源中存在的错误,现在* *我害怕:) – 2012-07-11 19:58:07
这不是播放音乐的唯一方式,但它是唯一的方法,如果您想同时做其他任何事情!换句话说,你在这里没有选择。学习如何多线程并获得一些乐趣。 – 2012-07-11 19:58:27
D'awww好吧我想我会学习一些东西haha – PinkElephantsOnParade 2012-07-11 19:59:42