1. 程式人生 > 程式設計 >Java利用讀寫的方式實現音訊播放程式碼例項

Java利用讀寫的方式實現音訊播放程式碼例項

這篇文章主要介紹了Java利用讀寫的方式實現音訊播放程式碼例項,文中通過示例程式碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下

public static void main(String[] args) {
  Audiotest at = new Audiotest("我在測試時,這裡必須是碟符的音訊檔案");
  at.start();
}
import java.io.File;
import java.io.IOException;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;

public class Audiotest extends Thread {
  
  //1.定義音訊檔案的變數,變數需要:一個用於儲存音訊檔案物件名字的String物件 filename
  private String filename;
  //2.建構函式,初始化filename
  public Audiotest(String filename){
    this.filename = filename;
  }
  
  @Override
  public void run() {
    //1.定義一個檔案物件引用,指向名為filename那個檔案
    File sourceFile = new File(filename);
    //定義一個AudioInputStream用於接收輸入的音訊資料
    AudioInputStream audioInputStream = null;
    //使用AudioSystem來獲取音訊的音訊輸入流
    try {
      audioInputStream = AudioSystem.getAudioInputStream(sourceFile);
    } catch (UnsupportedAudioFileException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    //4,用AudioFormat來獲取AudioInputStream的格式
    AudioFormat format = audioInputStream.getFormat();
    //5.源資料行SoureDataLine是可以寫入資料的資料行
    SourceDataLine auline = null;
    //獲取受資料行支援的音訊格式DataLine.info
    DataLine.Info info = new DataLine.Info(SourceDataLine.class,format);

    //獲得與指定info型別相匹配的行
    try {
      auline = (SourceDataLine) AudioSystem.getLine(info);
      //開啟具有指定格式的行,這樣可使行獲得所有所需系統資源並變得可操作
      auline.open();
    } catch (LineUnavailableException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    //允許某一個數據行執行資料i/o
    auline.start();

    //寫出資料
    int nBytesRead = 0;
    byte[] abData = new byte[2];
    //從音訊流讀取指定的最大數量的資料位元組,並將其放入給定的位元組陣列中。
    try {
      while (nBytesRead != -1) {
        nBytesRead = audioInputStream.read(abData,abData.length);
        //通過此源資料行將資料寫入混頻器
        if (nBytesRead >= 0)
          auline.write(abData,nBytesRead);
      }
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      auline.drain();
      auline.close();
    }  }
}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。