2014-09-02 74 views
-4

我在這裏閱讀了很多帖子,他們都是不完整或部分工作。我有一些短暫的「嘟嘟聲」,需要在我的程序中播放時才需要。問題在於我經常需要將它們一起播放(同時播放多個節目),並且無需停止節目的其餘部分。如何在後臺播放Java中的wav

幫助將非常感激!

private final int BUFFER_SIZE = 128000; 
private File soundFile; 
private AudioInputStream audioStream; 
private AudioFormat audioFormat; 
private SourceDataLine sourceLine; 
public void playSound(String filename) 
    { 

     String strFilename = filename; 

     try { 
      soundFile = new File(strFilename); 
     } catch (Exception e) { 
      e.printStackTrace(); 
      System.exit(1); 
     } 

     try { 
      audioStream = AudioSystem.getAudioInputStream(soundFile); 
     } catch (Exception e){ 
      e.printStackTrace(); 
      System.exit(1); 
     } 

     audioFormat = audioStream.getFormat(); 

     DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat); 
     try { 
      sourceLine = (SourceDataLine) AudioSystem.getLine(info); 
      sourceLine.open(audioFormat); 
     } catch (LineUnavailableException e) { 
      e.printStackTrace(); 
      System.exit(1); 
     } catch (Exception e) { 
      e.printStackTrace(); 
      System.exit(1); 
     } 

     sourceLine.start(); 

     int nBytesRead = 0; 
     byte[] abData = new byte[BUFFER_SIZE]; 
     while (nBytesRead != -1) { 
      try { 
       nBytesRead = audioStream.read(abData, 0, abData.length); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
      if (nBytesRead >= 0) { 
       @SuppressWarnings("unused") 
       int nBytesWritten = sourceLine.write(abData, 0, nBytesRead); 
      } 
     } 

     sourceLine.drain(); 
     sourceLine.close(); 
    } 
+0

一旦你提供了代碼,它會更容易幫助你。 – ortis 2014-09-02 12:50:48

+1

你真正的問題是什麼? – 2014-09-02 12:51:25

+1

@AlexisLeclerc毫無疑問...他希望我們爲他編碼。 Duh – 2014-09-02 12:51:58

回答

0

你可以嘗試的一個想法是用AudioStreams創建幾個線程。

當需要播放「嗶聲」時,您可以執行一個或多個線程。