java 語音採集組件

class Capture implements Runnable{html

TargetDateLine line;//能夠從中讀取音頻數據的某種類型的 DataLinejava

Thread thread;網絡

Socket socket;socket

BufferedOutputStream captrueOutputStream;ide

Captrue(Socket socket){//構造函數,取得socket函數

   this.socket=socket;this

}線程

public void start(){//啓動線程code

   thread=new Thread(this);orm

   thread.setName(「Capture」);

   thread.start();

}

public void stop(){//中止線程

   thread=null;

}

public void run(){

   try{

      captrueOutputStream=new BufferedOutputStream(s.getOutputStream())//創建輸出流

}catch(IOException e){

   return;

}

AudioFormat format =new AudioFormat(8000,16,2,true,true);//AudioFormat(float sampleRate, int sampleSizeInBits, int channels, boolean signed, boolean bigEndian)
        DataLine.Info info = new DataLine.Info(TargetDataLine.class,format);

        try {
            line = (TargetDataLine) AudioSystem.getLine(info);
            line.open(format, line.getBufferSize());
        } catch (Exception ex) {
            return;
        }

   byte[] data = new byte[1024];//此處的1024能夠狀況進行調整,應跟下面的1024應保持一致
           int numBytesRead=0;
           line.start();

           while (thread != null) {
               numBytesRead = line.read(data, 0,128);//取數據(1024)的大小直接關係到傳輸的速度,通常越小越快,
               try {
                 captrueOutputStream.write(data, 0, numBytesRead);//寫入網絡流
               }
               catch (Exception ex) {
                   break;
               }
           }

           line.stop();
           line.close();
           line = null;

           try {                captrueOutputStream.flush();                captrueOutputStream.close();            } catch (IOException ex) {                ex.printStackTrace();            }        }      }

相關文章
相關標籤/搜索