Android - 通过听筒播放音频

26 浏览
0 Comments

Android - 通过听筒播放音频

我目前有一段代码,使用AudioRecord类从设备的麦克风读入录音,并使用AudioTrack类将其播放出来。

我的问题是,当我播放时,声音通过扬声器播放。

我希望它通过设备的听筒播放。

以下是我的代码:

public class LoopProg extends Activity {
 boolean isRecording; //当前未使用
 AudioManager am;
 int count = 0;
 /** 在创建活动时调用 */
 @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        am.setMicrophoneMute(true);
        while(count <= 1000000){
        Record record = new Record();  
        record.run();
        count ++;
        Log.d("COUNT", "Count is : " + count);
        }
    } 
   public class Record extends Thread{
      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);
      AudioRecord arec = new AudioRecord(MediaRecorder.AudioSource.MIC, 11025, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT, buffersize);
      AudioTrack atrack = new AudioTrack(AudioManager.STREAM_MUSIC, 11025, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT, buffersize, AudioTrack.MODE_STREAM);
      am.setRouting(AudioManager.MODE_NORMAL,1, AudioManager.STREAM_MUSIC);
      int ok = am.getRouting(AudioManager.ROUTE_EARPIECE);
      Log.d("ROUTING", "getRouting = " + ok);
      setVolumeControlStream(AudioManager.STREAM_VOICE_CALL);
      //am.setSpeakerphoneOn(true);
      Log.d("SPEAKERPHONE", "Is speakerphone on? : " + am.isSpeakerphoneOn());
      am.setSpeakerphoneOn(false);
      Log.d("SPEAKERPHONE", "Is speakerphone on? : " + am.isSpeakerphoneOn());
      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);
                         }
      arec.stop();
      atrack.stop();
      isRecording = false;
      }
   } 
}

如您所见,我已尝试使用AudioManager类及其方法,包括已弃用的setRouting方法,但没有任何效果,setSpeakerphoneOn方法似乎没有任何效果,路由方法也是如此。

有人有任何关于如何使其通过听筒而不是扬声器播放的想法吗?

0