how to play sound from microphone to speaker directly on android?

懵懂的女人 提交于 2019-12-03 04:32:49

问题


in my application, I need to direct sound from microphone directly to speaker. No other actions. I found a way to direct sound from microphone to earpiece by playing a file and setting speaker off. So I guess speaker can work similarly. However I don' know how to get rid of the playing file thing. Thank you.

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:


use AudioRecord & AudioTrack to record & play (change to ..._MUSIC if speaker needed

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);
               }
     } 


来源:https://stackoverflow.com/questions/4654779/how-to-play-sound-from-microphone-to-speaker-directly-on-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!