2011-06-15 99 views

回答

0

您可以使用AudioRecord來讀取字節的音頻數據字節,這裏是一些示例代碼。

// calculate the minimum buffer 
int minBuffer = AudioRecord.getMinBufferSize(SAMPLE_RATE, CHANNEL_CONFIG, AUDIO_FORMAT); 

// initialise audio recorder and start recording 
AudioRecord mRec = new AudioRecord(AUDIO_SOURCE, SAMPLE_RATE, 
       CHANNEL_CONFIG, AUDIO_FORMAT, 
       minBuffer); 
mRec.startRecording(); 
byte[] pktBuf = new byte[pktSizeByte]; 
boolean ok; 
// now you can start reading the bytes from the AudioRecord 
while (!finished) { 
    // fill the pktBuf 
    readFully(pktBuf, 0, pktBuf.length); 
    // make a copy 
    byte[] pkt = Arrays.copyOf(pktBuf, pktBuf.length); 
    // do anything with the byte[] ... 
} 

由於到read()單個呼叫可能無法獲得足夠的數據來填充byte[] pktBuf,我們可能需要多次讀取填充緩衝區。在這種情況下,我使用了一個輔助函數「readFully」來確保填充緩衝區。根據你想與你的代碼做什麼,不同的策略可用於...

/* fill the byte[] with recorded audio data */ 
private void readFully(byte[] data, int off, int length) { 
    int read; 
    while (length > 0) { 
     read = mRec.read(data, off, length); 
     length -= read; 
     off += read; 
    } 
} 

記得撥打mRec.stop()完成後停止AudioRecorder。希望有所幫助。