1

我有一个主要发生游戏逻辑的游戏。我刚刚根据我发现的文档添加了声音播放:

//////////////////////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库或其他一些聪明的解决方案可以避免在这种情况下多线程?

4

2 回答 2

3

是的,您需要使用单独的线程。没有什么好害怕的。Java中的多线程是小菜一碟。查看并发包。

http://docs.oracle.com/javase/tutorial/essential/concurrency/

于 2012-07-11T19:59:47.693 回答
0

当心:知道如何启动一个线程和知道如何安全地多线程你的程序是两件不同的事情。现在,请确保避免从多个线程中触摸相同的音乐。

于 2012-07-11T20:10:05.960 回答