如何在Android上直接从麦克风到扬声器播放声音?

时间:2011-01-11 06:19:16

标签: android microphone speaker

在我的应用程序中,我需要将麦克风的声音直接传送到扬声器。没有其他行动。 我找到了一种方法,通过播放文件和关闭扬声器将声音从麦克风传送到听筒。所以我猜扬声器的工作方式类似。但是我不知道如何摆脱播放文件的事情。谢谢。

speaker() {
    m_audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
    m_audioManager.setSpeakerphoneOn(true);  // not needed I think
    //m_audioManager.setRouting(AudioManager.MODE_NORMAL, AudioManager.ROUTE_EARPIECE, AudioManager.ROUTE_ALL); earpiece need this?
    setVolumeControlStream(AudioManager.STREAM_VOICE_CALL);
    m_audioManager.setMode(AudioManager.MODE_IN_CALL);

1 个答案:

答案 0 :(得分:15)

使用AudioRecord& AudioTrack记录&播放(如果需要演讲者,则改为...... _ MUSIC

static final int bufferSize = 200000;
final short[] buffer = new short[bufferSize];
short[] readBuffer = new short[bufferSize];
public void run() {
     isRecording = true;
     android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO);
     int buffersize = AudioRecord.getMinBufferSize(11025, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT);
     arec = new AudioRecord(MediaRecorder.AudioSource.MIC, 11025, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT, buffersize);
     atrack = new AudioTrack(AudioManager.STREAM_VOICE_CALL, 11025, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT, buffersize, AudioTrack.MODE_STREAM);
     atrack.setPlaybackRate(11025);
     byte[] buffer = new byte[buffersize];
     arec.startRecording();
     atrack.play();
           while(isRecording) {
               arec.read(buffer, 0, buffersize);
               atrack.write(buffer, 0, buffer.length);
               }
     }