类似对讲机功能按下开始说话,并且同时播放,一个很小的简单功能,使用AudioRecord与AudioTrack,
文章后附上DEMO
直接看代码,一个类:
public class MainActivity extends AppCompatActivity {
private Button btnSatrt,btnStop;
private TextView text;
boolean mRunning = true;
void micLoopBack()
{
//这两句话的作用是打开设备扬声器
AudioManager service = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
service.setSpeakerphoneOn(true);
Log.v("AABBCC","选中了");
int SAMPLE_RATE = 8000;
int BUF_SIZE = 1024;
//计算缓冲区尺寸
int bufferSize = AudioRecord.getMinBufferSize(SAMPLE_RATE,
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT);
bufferSize = Math.max(bufferSize,
AudioTrack.getMinBufferSize(SAMPLE_RATE,
AudioFormat.CHANNEL_IN_MONO,AudioFormat.ENCODING_PCM_16BIT));
bufferSize = Math.max(bufferSize, BUF_SIZE);
byte[] buffer = new byte[bufferSize];
//创建音频采集设备,输入源是麦克风
AudioRecord m_record = new AudioRecord(MediaRecorder.AudioSource.MIC,
SAMPLE_RATE, AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT, bufferSize);
//创建音频播放设备
AudioTrack m_track = new AudioTrack(AudioManager.STREAM_VOICE_CALL,
SAMPLE_RATE,
AudioFormat.CHANNEL_OUT_MONO,
AudioFormat.ENCODING_PCM_16BIT,
bufferSize,
AudioTrack.MODE_STREAM);
m_track.setPlaybackRate(SAMPLE_RATE);
//一边采集,一边播放
m_record.startRecording();
m_track.play();
//需要停止的时候,把mRunning置为false即可。
while(mRunning)
{
int readSize = m_record.read(buffer, 0, bufferSize);
if(readSize > 0)
m_track.write(buffer, 0, readSize);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSatrt = findViewById(R.id.btn_start);
btnStop = findViewById(R.id.btn_stop);
text = findViewById(R.id.Text_0);
btnSatrt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
text.setText("启动");
Log.v("AABBCC","启动");
mRunning = true;
new Thread(runnable).start();
}
});
btnStop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
text.setText("关闭");
Log.v("AABBCC","关闭");
mRunning = false;
//new Thread(runnable).stop();
}
});
}
Runnable runnable = new Runnable() {
@Override
public void run() {
micLoopBack();
}
};
}
-END