AudioRecord是Android中用于音频录制的类,它的主要作用是捕获来自设备麦克风或其他音频源的音频数据,并将其保存为PCM格式的音频流,以供后续处理或存储。
以下是关于AudioRecord的一些常见用途和基本使用方法:
作用和用途:
音频录制:AudioRecord可以用于录制来自麦克风、耳机麦克风或其他音频输入源的音频。这在开发语音通话、语音识别、音频笔记、音频流媒体等应用中非常有用。
声音分析:通过捕获音频数据,你可以进行声音分析,如检测音频的频谱、音量、音调等特征,用于声音处理和分析应用。
实时音频处理:你可以将录制的音频数据传递给其他音频处理库或自定义算法,以进行实时音频处理,如降噪、回声消除、音频效果等。
音频存储:你可以将录制的音频数据保存为音频文件,例如.wav或.mp3,以便后续播放或分享。
需要权限:
工具类:
package com.realtop.translatemodule.utils;
import android.annotation.SuppressLint;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.util.Log;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.security.auth.login.LoginException;
public class AudioRecordUtils {
private static final String TAG = "AudioRecordActivity";
private static final int SAMPLE_RATE = 16000; // 采样率为16K
private static final int CHANNEL_CONFIG = AudioFormat.CHANNEL_IN_MONO;
private static final int AUDIO_FORMAT = AudioFormat.ENCODING_PCM_16BIT;
private static final int BUFFER_SIZE = AudioRecord.getMinBufferSize(SAMPLE_RATE, CHANNEL_CONFIG, AUDIO_FORMAT);
private AudioRecord audioRecord;
private boolean isRecording = false;
private Thread recordingThread;
private FileOutputStream fileOutputStream;
@SuppressLint("MissingPermission")
public synchronized void startRecording(String filePath) {
if (isRecording) {
Log.i(TAG, "startRecording: ing stop enter");
return;
}
isRecording = true;
// 初始化 AudioRecord 对象
audioRecord = new AudioRecord(
MediaRecorder.AudioSource.VOICE_COMMUNICATION,
SAMPLE_RATE,
CHANNEL_CONFIG,
AUDIO_FORMAT,
BUFFER_SIZE
);
audioRecord.startRecording();
// 初始化输出文件
try {
fileOutputStream = new FileOutputStream(filePath, true);
} catch (FileNotFoundException e) {
Log.i(TAG, "startRecording: error:" + e.getMessage());
}
recordingThread = new Thread(() -> {
byte[] buffer = new byte[BUFFER_SIZE];
while (isRecording) {
int bytesRead = audioRecord.read(buffer, 0, BUFFER_SIZE);
if (bytesRead != AudioRecord.ERROR_INVALID_OPERATION) {
try {
fileOutputStream.write(buffer, 0, bytesRead);
} catch (IOException e) {
Log.i(TAG, "startRecording: error:" + e.getMessage());
}
}
}
Log.i(TAG, "startRecording: record thread end");
});
recordingThread.start();
Log.i(TAG, "startRecording: start");
}
public synchronized void stopRecording() {
if (!isRecording) {
Log.i(TAG, "stopRecording: end ing");
return;
}
isRecording = false;
try {
recordingThread.join(); // 精华部分
audioRecord.stop();
fileOutputStream.close();
audioRecord.release();
Log.i(TAG, "stopRecording: end");
} catch (Exception e) {
e.printStackTrace();
Log.i(TAG, "stopRecording: error:" + e.getMessage());
}
}
}