這是一個直接播放麥克風采集到的聲音線程類:
class RecordThread extends Thread{
static final int frequency = 44100;
static final int channelConfiguration = AudioFormat.CHANNEL_CONFIGURATION_MONO;
static final int audioEncoding = AudioFormat.ENCODING_PCM_16BIT;
@Override
public void run() {
// TODO Auto-generated method stub
int recBufSize = AudioRecord.getMinBufferSize(frequency,
channelConfiguration, audioEncoding)*2;
int plyBufSize = AudioTrack.getMinBufferSize(frequency,
channelConfiguration, audioEncoding)*2;
AudioRecord audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, frequency,
channelConfiguration, audioEncoding, recBufSize);
AudioTrack audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, frequency,
channelConfiguration, audioEncoding, plyBufSize, AudioTrack.MODE_STREAM);
byte[] recBuf = new byte[recBufSize];
audioRecord.startRecording();
audioTrack.play();
while(true){
int readLen = audioRecord.read(recBuf, 0, recBufSize);
audioTrack.write(recBuf, 0, readLen);
}
audioTrack.stop();
audioRecord.stop();
}
}
使用的時候,這樣就行:
RecordThread rec = new RecordThread();
rec.start();
需要在AndroidManifest.xml檔案中添加路由權限:
<uses-permission android:name="android.permission.RECORD_AUDIO"/>