Androidプラットフォームで音声録音機能を実装する場合、android.media.MediaRecorderクラスを使用するのが最も一般的で効率的な手法です。ここでは、ユーザーがボタンを長押ししている間だけ録音を行う、いわゆる「プッシュ・トゥ・トーク」形式のユーザーインターフェースを想定した実装手順を解説します。
1. レイアウトの定義
まず、録音操作を行うためのボタンを配置します。以下の例では、画面中央に録音開始のトリガーとなるButtonを配置しています。
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<Button
android:id="@+id/record_action_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="20dp"
android:text="REC"
android:textSize="24sp" />
</RelativeLayout>
2. タッチイベントの処理
録音の開始と終了を制御するために、ボタンにOnTouchListenerを設定します。MotionEvent.ACTION_DOWNで指が触れたときに録音を開始し、MotionEvent.ACTION_UPで離れたときに録音を停止するようにロジックを組みます。
private void setupRecordingUI() {
Button recordButton = findViewById(R.id.record_action_button);
recordButton.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
// 録音処理の開始
initiateAudioCapture();
return true;
case MotionEvent.ACTION_UP:
// 録音処理の停止
terminateAudioCapture();
return true;
}
return false;
}
});
}
3. 録音開始ロジックの実装
録音を開始する際は、保存先ディレクトリの確認、MediaRecorderのインスタンス化、および各種パラメータの設定(音源、出力フォーマット、エンコーダーなど)が必要になります。
private MediaRecorder voiceRecorder;
private File outputAudioFile;
private void initiateAudioCapture() {
// 外部ストレージの状態確認
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
return;
}
try {
// 保存先のディレクトリ構造を作成
File storageDir = new File(getExternalFilesDir(null), "recordings");
if (!storageDir.exists()) {
storageDir.mkdirs();
}
// タイムスタンプを基にファイル名を生成
String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
outputAudioFile = new File(storageDir, "VOICE_" + timestamp + ".amr");
voiceRecorder = new MediaRecorder();
// マイクを音源に設定
voiceRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
// 出力形式を3GPに設定
voiceRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
// エンコーダーをAMR_NBに設定
voiceRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
// 出力パスの指定
voiceRecorder.setOutputFile(outputAudioFile.getAbsolutePath());
voiceRecorder.prepare();
voiceRecorder.start();
} catch (Exception e) {
e.printStackTrace();
}
}
4. 録音停止とリソースの解放
録音を終了する際は、stop()メソッドを呼び出した後、リソースを適切に解放するためにrelease()を実行することが重要です。これにより、メモリリークやデバイスの占有を防ぎます。
private void terminateAudioCapture() {
if (voiceRecorder != null) {
try {
voiceRecorder.stop();
} catch (RuntimeException stopException) {
// 録音時間が極端に短い場合に発生する例外のハンドリング
if (outputAudioFile.exists()) {
outputAudioFile.delete();
}
} finally {
voiceRecorder.release();
voiceRecorder = null;
}
}
}
なお、実際の実装においては、RECORD_AUDIOおよびWRITE_EXTERNAL_STORAGE(Android 10未満の場合)などのパーミッションをAndroidManifest.xmlに記述し、実行時にユーザーから権限を取得する処理を追加する必要があります。生成されたAMRファイルや3GPファイルは、標準的なメディアプレイヤーで再生可能です。