2012-01-19 266 views
0

我有五個wav文件。我想使用sourceDataLine從單個Java程序中串行播放它們。但是我的程序沒有保持正確的順序。任何人都可以提供我的代碼段?在java中播放聲音

+7

號向我們展示你的** **代碼。 –

+0

爲了更快得到更好的幫助,請發佈[SSCCE](http://sscce.org/)。雖然使它爲2個聲音樣本,而不是5. –

回答

3

您是否檢查Documentation

嘗試這個例子從here

import java.io.*; 
import javax.sound.sampled.*; 
/** 
* Use SourceDataLine to read line-by-line from the external sound file.  
*/ 
public class SoundLineTest { 
    public static void main(String[] args) { 
     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("gameover.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(); 
     } 
    } 
} 
+1

這是最好的評論,不是? :-) – Scorpion

+0

@Scorpio:我還沒有完成。 – CloudyMarble

+0

+1優秀的編輯。 –