Androidで自分の声をフィードバックする方法
Androidのアプリで、録音した音声を、その場で聞く方法をまとめました。
そんなに難しいプログラムではありません。
final static int SAMPLING_RATE = 44100; private AudioRecord audioRec = null; private boolean bIsRecording = false; private int bufSize; private AudioTrack audioTrack; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 画面表示 setContentView(R.layout.activity_main); // 録音するよ bufSize=AudioRecord.getMinBufferSize( SAMPLING_RATE, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT); // 再生するよ audioTrack = new AudioTrack(AudioManager.STREAM_VOICE_CALL, SAMPLING_RATE, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT, bufSize, AudioTrack.MODE_STREAM); audioTrack.play(); } @Override protected void onResume() { super.onResume(); //AudioRecordの作成 audioRec = new AudioRecord( MediaRecorder.AudioSource.MIC, SAMPLING_RATE, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, bufSize * 2); // 2倍にしないと処理落ちするらしい。 if (AutomaticGainControl.isAvailable()) { AutomaticGainControl agc = AutomaticGainControl.create(audioRec.getAudioSessionId()); agc.setEnabled(true); Log.i("自動利得制御", "有効にしました。"); } else { Log.i("自動利得制御", "対応していない端末です。"); } audioRec.startRecording(); bIsRecording = true; new Thread(new Runnable() { @Override public void run() { short buf[] = new short[bufSize]; while (bIsRecording) { int numRead = audioRec.read(buf, 0, buf.length); float gain = 0.21f; if (numRead > 0) { for (int i = 0; i < numRead; ++i) { buf[i] = (short)Math.min((int)(buf[i] * gain), (int)Short.MAX_VALUE); } } // Log.d("audiorecord", String.valueOf(buf.length)); Log.i("audiorecord", String.valueOf(buf[0])); } // 録音停止 audioRec.stop(); audioRec.release(); } }).start(); } @Override protected void onPause() { super.onPause(); if (bIsRecording) { bIsRecording = false; } }