MicropRunnable.java:
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioRecord;
import android.media.AudioTrack;
import android.media.MediaRecorder;
public class MicropRunnable implements Runnable {
// 是否录放的标记
boolean isRecording = false;
static final int frequency = 44100;
@SuppressWarnings("deprecation")
static final int channelConfiguration = AudioFormat.CHANNEL_CONFIGURATION_MONO;
static final int audioEncoding = AudioFormat.ENCODING_PCM_16BIT;
// 定义录放音缓冲区大小
int recBufSize, playBufSize;
// 实例化录音对象
AudioRecord audioRecord;
// 实例化播放对象
AudioTrack audioTrack;
public MicropRunnable() {
// 调用getMinBufferSize方法获得录音的最小缓冲空间
recBufSize = AudioRecord.getMinBufferSize(frequency, channelConfiguration, audioEncoding);
// 调用getMinBufferSize方法获得放音最小的缓冲区大小
playBufSize = AudioTrack.getMinBufferSize(frequency, channelConfiguration, audioEncoding);
// 调用构造函数实例化录音对象
int nMinBufSize = AudioRecord.getMinBufferSize(frequency, AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT);
audioRecord = new AudioRecord(MediaRecorder.AudioSource.VOICE_COMMUNICATION, frequency,
AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, nMinBufSize);
// 调用构造函数实例化放音对象,以听筒模式播放
audioTrack = new AudioTrack(AudioManager.STREAM_VOICE_CALL, frequency, channelConfiguration, audioEncoding,
playBufSize, AudioTrack.MODE_STREAM);
}
@Override
public void run() {
try {
byte[] buffer = new byte[recBufSize];
audioRecord.startRecording();// 开始录制
audioTrack.play();// 开始播放
this.isRecording = true;
while (isRecording) {
// 从MIC保存数据到缓冲区
int bufferReadResult = audioRecord.read(buffer, 0, recBufSize);
byte[] tmpBuf = new byte[bufferReadResult];
System.arraycopy(buffer, 0, tmpBuf, 0, bufferReadResult);
// 写入数据就播放
audioTrack.write(tmpBuf, 0, tmpBuf.length);
}
audioTrack.stop();
audioRecord.stop();
} catch (Throwable t) {
t.printStackTrace();
}
}
// 停止方法
public void no() {
isRecording = false;
}
}
test.java:
private MicropRunnable run_Metned = new MicropRunnable();
private AudioManager audioManager;
start_test() {
openSpeaker();
Thread thread = new Thread(run_Metned); //将麦克风开启方法加入线程体中
thread.start();
}
public void openSpeaker() {
try {
// 判断扬声器是否在打开
audioManager.setMode(AudioManager.ROUTE_SPEAKER);
// 获取当前通话音量
int currVolume = 0;
currVolume = audioManager.getStreamVolume(AudioManager.STREAM_VOICE_CALL);
if (!audioManager.isSpeakerphoneOn()) {
audioManager.setSpeakerphoneOn(true);
audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL,
audioManager.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL),
AudioManager.STREAM_VOICE_CALL);
}
} catch (Exception e) {
e.printStackTrace();
}
}
AndroidManifest里加上权限:
THE END