騒音計作成、AudioRecordの利用、マイクで音声を取り込んで処理する。

騒音計の作成でAudioRecordの利用して、マイクで音声を取り込んで処理するアプリを作ったのでその時のまとめ。

AudioRecordの賢い利用方法

  1. 排他制御。
  2. プロセスの優先度を上げる。
  3. バッファサイズの取得。
  4. AudioRecordのインスタンス作成。
  5. AudioRecordの起動。
  6. 排他制御して、バッファに読み込み、中身を処理する。

1.排他制御。

synchronized (mutex) {
while (!this.isRecording) {
try {
mutex.wait();
} catch (InterruptedException e) {
throw new IllegalStateException(“エラー”, e);
}
}
}

2.プロセスの優先度を上げる。

android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO);

3.バッファサイズの取得。

int bufferRead = 0;

int bufferSize = AudioRecord.getMinBufferSize(
11025,
AudioFormat.CHANNEL_CONFIGURATION_MONO,
AudioFormat.ENCODING_PCM_16BIT
);

4.AudioRecordのインスタンス作成。

recordInstance = new AudioRecord(
MediaRecorder.AudioSource.MIC,
11025,
AudioFormat.CHANNEL_CONFIGURATION_MONO,
AudioFormat.ENCODING_PCM_16BIT,
bufferSize
);

5.AudioRecordの起動。

recordInstance.startRecording();

6.排他制御して、バッファに読み込み、中身を処理する。

synchronized (mutex) {
if (this.isPaused) {
try {
mutex.wait(500);
} catch (InterruptedException e) {
throw new IllegalStateException(“Wait() interrupted!”,
e);
}
continue;
}
}
tempBuffer = null;
tempBuffer = new short[bufferSize];

bufferRead = recordInstance.read(tempBuffer, 0, bufferSize);
long sum = 0;

//平均値から取得している。

for(int i = 0; i < bufferSize; i++){
sum += Math.abs(tempBuffer[i]);
}
short avg = (short) (sum / bufferSize);

if( mListener != null){
mListener.OnReachedVolum(avg);音を得るたびに実行する自作メソッド。
}

違うactivityを起動するなどして、pause()中に、再起動をかけて新しくAudioRecordを起動した場合にRuntimeExceptionのエラーが起こってしまう。

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です