1. 程式人生 > >Java-播放WAV音訊

Java-播放WAV音訊

public class Test {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        AePlayWave apw=new AePlayWave("aaa.wav");
        apw.start();
    }

}

class AePlayWave extends Thread {

    private String filename;
    public AePlayWave
(String wavfile) { filename = wavfile; } public void run() { File soundFile = new File(filename); // 獲取音訊輸入流 AudioInputStream audioInputStream = null; try { audioInputStream = AudioSystem.getAudioInputStream(soundFile); } catch (Exception e1) { e1.printStackTrace(); return
; } // 獲取音訊編碼物件 AudioFormat format = audioInputStream.getFormat(); // 設定資料輸入 SourceDataLine auline = null; DataLine.Info info = new DataLine.Info(SourceDataLine.class, format); try { auline = (SourceDataLine) AudioSystem.getLine(info); auline.open(format); } catch
(Exception e) { e.printStackTrace(); return; } auline.start(); /* * 從輸入流中讀取資料傳送到混音器 */ int nBytesRead = 0; byte[] abData = new byte[512]; try { while (nBytesRead != -1) { nBytesRead = audioInputStream.read(abData, 0, abData.length); if (nBytesRead >= 0) auline.write(abData, 0, nBytesRead); } } catch (IOException e) { e.printStackTrace(); return; } finally { // 清空資料緩衝,並關閉輸入 auline.drain(); auline.close(); } } }