2011-12-21 134 views
1

我有一堆代碼,運行時會產生程序聲音。不幸的是,它只持續幾秒鐘。理想情況下,它會運行,直到我告訴它停止。我不是在討論循環,生成它的算法目前提供了2^64個樣本,所以在可預見的將來它不會耗盡。 AudioInputStream的構造函數需要第三個輸入,我可以理想地刪除它。我只能提供一個很大的數字,但這似乎是錯誤的方式去做。Java長度無限制AudioInputStream

我曾考慮過使用SourceDataLine,但算法理想情況下會按需調用,不會在前面運行並寫入路徑。思考?

回答

0

看來我已經回答了我自己的問題。

經過進一步研究,使用SourceDataLine是一條路要走,因爲它會阻止,只要你給它足夠的工作。

道歉缺乏適當的Javadoc。

class SoundPlayer 
{ 
    // plays an InputStream for a given number of samples, length 
    public static void play(InputStream stream, float sampleRate, int sampleSize, int length) throws LineUnavailableException 
    { 
     // you can specify whatever format you want...I just don't need much flexibility here 
     AudioFormat format = new AudioFormat(sampleRate, sampleSize, 1, false, true); 
     AudioInputStream audioStream = new AudioInputStream(stream, format, length); 
     Clip clip = AudioSystem.getClip(); 
     clip.open(audioStream); 
     clip.start(); 
    } 

    public static void play(InputStream stream, float sampleRate, int sampleSize) throws LineUnavailableException 
    { 
     AudioFormat format = new AudioFormat(sampleRate, sampleSize, 1, false, true); 
     SourceDataLine line = AudioSystem.getSourceDataLine(format); 
     line.open(format); 
     line.start(); 
     // if you wanted to block, you could just run the loop in here 
     SoundThread soundThread = new SoundThread(stream, line); 
     soundThread.start(); 
    } 

    private static class SoundThread extends Thread 
    { 
     private static final int buffersize = 1024; 

     private InputStream stream; 
     private SourceDataLine line; 

     SoundThread(InputStream stream, SourceDataLine line) 
     { 
      this.stream = stream; 
      this.line = line; 
     } 

     public void run() 
     { 
      byte[] b = new byte[buffersize]; 
      // you could, of course, have a way of stopping this... 
      for (;;) 
      { 
       stream.read(b); 
       line.write(b, 0, buffersize); 
      } 
     } 
    } 
} 
+0

我想我會在兩天內接受這個答案......除非有人提出了一個更好的解決方案。 – skeggse 2011-12-21 08:07:23