簡體   English   中英

多線程只能在Java中播放背景音樂?

[英]Multithreading only way to play background music in 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庫或其他一些聰明的解決方案來避免在這種情況下多線程?

是的,您需要使用單獨的線程。 沒有什么可怕的。 Java中的多線程是一塊蛋糕。 查看並發包。

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

注意:知道如何啟動線程並知道如何安全地多線程化程序是兩回事。 現在,請確保避免從多個線程觸摸相同的音樂。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM