我尝试开发扬声器应用程序。音频输入内置于手机麦克风中。音频输出内置于手机扬声器。我开发了那个应用程序,但效果不佳。我说"你好"电话麦克风没有回应。我下次尝试吹空气给手机麦克风。响应声音有很多回声和空气噪音。如何解决这个问题。
更新
一些设备响应声音是不同的。我不知道这取决于设备规格。
参考:
Android AudioRecord class - process live mic audio quickly, set up callback function
Live Audio Recording and Playing in Android and Thread & callback handling
我的代码:MainActivity.java
package bm.app.loudspeaker;
import android.app.Activity;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioRecord;
import android.media.AudioTrack;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ToggleButton;
public class MainActivity extends Activity {
Thread m_thread;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
m_thread = new Thread(new Runnable() {
@Override
public void run() {
loopBack();
}
});
final ToggleButton butSwitch = (ToggleButton)findViewById(R.id.butSwitch);
butSwitch.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (butSwitch.isChecked()) {
m_thread.start();
}
else{
}
}
});
}
boolean m_isRun = true;
int bufferSize = 0;
int SAMPLE_RATE = 8000;
AudioRecord m_record;
AudioTrack m_track;
byte[] buffer;
int ix = 0;
public void loopBack(){
try {
bufferSize = AudioRecord.getMinBufferSize(SAMPLE_RATE, AudioFormat.CHANNEL_CONFIGURATION_MONO,
AudioFormat.ENCODING_PCM_16BIT);
// if (bufferSize <= BUF_SIZE) {
// bufferSize = BUF_SIZE;
// }
Log.i("LOG","Initializing Audio Record and Audio Playing objects");
m_record = new AudioRecord(MediaRecorder.AudioSource.MIC, SAMPLE_RATE, AudioFormat.CHANNEL_CONFIGURATION_MONO
, AudioFormat.ENCODING_PCM_16BIT, bufferSize * 1);
m_track = new AudioTrack(AudioManager.STREAM_MUSIC, SAMPLE_RATE, AudioFormat.CHANNEL_CONFIGURATION_MONO
, AudioFormat.ENCODING_PCM_16BIT, bufferSize * 1
, AudioTrack.MODE_STREAM);
m_track.setPlaybackRate(SAMPLE_RATE);
m_record.startRecording();
Log.i("LOG","Audio Recording started");
m_track.play();
Log.i("LOG","Audio Playing started");
buffer = new byte[bufferSize];
while (m_isRun) {
m_record.read(buffer, 0, bufferSize);
m_track.write(buffer, 0, buffer.length);
}
Log.i("LOG", "loopback exit");
} catch (Exception e) {
// TODO: handle exception
}
}
}