|
边录音边播放 功能
//由于没有时间,所以没有对代码进行优化和注释,等有时间在补上
public class YinPinHuiLuActivity extends Activity implements OnClickListener{
private static final String TAG = "YinPinHuiLuActivity";
private Button bt_exit;
//AudioRecord
protected int m_in_buf_size;
private AudioRecord m_in_rec;
private byte[] m_in_bytes;
private LinkedList<byte[]> m_in_q;
//AudioTrack
private int m_out_buf_size;
private AudioTrack m_out_trk;
private byte[] m_out_bytes;
private Thread record;
private Thread play;
private boolean flag = true;//让线程停止的标志
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.yinpinhuilu_testing);
this.setTitle("音频回路");
init();
record = new Thread(new recordSound());
play = new Thread(new playRecord());
record.start();
play.start();
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.bt_yinpinhuilu_testing_exit:
flag = false;
m_in_rec.stop();
m_in_rec = null;
m_out_trk.stop();
m_out_trk = null;
this.finish();
}
}
private void init(){
bt_exit = (Button)findViewById(R.id.bt_yinpinhuilu_testing_exit);
Log.i(TAG,"bt_exit===="+bt_exit);
bt_exit.setOnClickListener(this);
//AudioRecord
m_in_buf_size =AudioRecord.getMinBufferSize(8000,
AudioFormat.CHANNEL_CONFIGURATION_MONO,
AudioFormat.ENCODING_PCM_16BIT);
m_in_rec = new AudioRecord(MediaRecorder.AudioSource.MIC,
8000,
AudioFormat.CHANNEL_CONFIGURATION_MONO,
AudioFormat.ENCODING_PCM_16BIT,
m_in_buf_size) ;
m_in_bytes = new byte[m_in_buf_size] ;
m_in_q=new LinkedList<byte[]>();
//AudioTrack
m_out_buf_size = AudioTrack.getMinBufferSize(8000,
AudioFormat.CHANNEL_CONFIGURATION_MONO,
AudioFormat.ENCODING_PCM_16BIT);
m_out_trk = new AudioTrack(AudioManager.STREAM_MUSIC, 8000,
AudioFormat.CHANNEL_CONFIGURATION_MONO,
AudioFormat.ENCODING_PCM_16BIT,
m_out_buf_size,
AudioTrack.MODE_STREAM);
m_out_bytes=new byte[m_out_buf_size];
}
class recordSound implements Runnable{
@Override
public void run() {
Log.i(TAG,"........recordSound run()......");
byte [] bytes_pkg ;
// TODO Auto-generated method stub
m_in_rec.startRecording();
while(flag){
m_in_rec.read(m_in_bytes, 0, m_in_buf_size) ;
bytes_pkg = m_in_bytes.clone() ;
Log.i(TAG,"........recordSound bytes_pkg=="+bytes_pkg.length);
if(m_in_q.size() >= 2)
{
m_in_q.removeFirst();
}
m_in_q.add(bytes_pkg) ;
}
}
}
class playRecord implements Runnable{
@Override
public void run() {
// TODO Auto-generated method stub
Log.i(TAG,"........playRecord run()......");
byte [] bytes_pkg = null ;
m_out_trk.play() ;
while(flag) {
try
{
m_out_bytes = m_in_q.getFirst();
bytes_pkg = m_out_bytes.clone() ;
m_out_trk.write(bytes_pkg, 0, bytes_pkg.length) ;
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
}
}
几个参考网址:
http://edison-cool911.javaeye.com/blog/724855
http://www.javaeye.com/topic/665429
http://jakielong.javaeye.com/blog/734851
http://topic.csdn.net/u/20100719 ... 7-b24ce9da24b3.html
|
|