AudioRecord 说明

AudioRecord 类的主要功能是让应用能够管理音频资源,以便它们通过此类能够录制声音相关的硬件所收集的声音。录音过程中主要通过 read(byte[], int, int), read(short[], int, int), read(ByteBuffer, int) 中的一个方法去及时获取 AudioRecord 对象的录音数据,在录音前都必须先设定声音数据的存储格式。

AudioRecord 创建

构造函数

AudioRecord)(int audioSource, int sampleRateInHz, int channelConfig, int audioFormat, int bufferSizeInBytes)

  • audioSource 音频源:物理源音频信号,一般采用麦克风采集 ,参数值为MediaRecorder.AudioSource.MIC
  • sampleRateInHz 采样频率:音频的采样频率,采样频率越高,音质越高。常给的实例参数:44100、22050、11025、8000、4000等。
  • channelConfig 声道设置:双声道立体声(AudioFormat.CHANNEL_IN_MONO)、单声道(AudioFormat.CHANNEL_IN_STEREO)
  • audioFormat 编码制式和采样大小:采集的数据使用 PCM(脉冲编码调制) 编码,参数值为AudioFormat.ENCODING_PCM_16BIT、AudioFormat.ENCODING_PCM_8BIT、AudioFormat.ENCODING_PCM_FLOAT 等。
  • bufferSizeInBytes 缓冲区大小。可以从 AudioRecord.getMinBufferSize (int sampleRateInHz,nt channelConfig,int audioFormat) 获取。

AudioRecord 主要方法

  • startRecording() 开始录音
  • stop() 停止录音
  • read(…) 从硬件中读取录音数据
  • release() 释放 AudioRecord 资源文件

AudioRecord 实例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
//采样频率
private final static int AUDIO_SAMPLE_RATE = 16000;
//单声道
private final static int AUDIO_CHANNEL = AudioFormat.CHANNEL_IN_MONO;
//编码
private final static int AUDIO_ENCODING = AudioFormat.ENCODING_PCM_16BIT;
/**
* 创建录音文件
*
*/
public void createAudio() {
int bufferSizeInBytes = AudioRecord.getMinBufferSize(AUDIO_SAMPLE_RATE, AUDIO_CHANNEL, AUDIO_ENCODING);
AudioRecord audioRecord = new AudioRecord(AUDIO_INPUT, AUDIO_SAMPLE_RATE, AUDIO_CHANNEL, AUDIO_ENCODING, bufferSizeInBytes);
}
// 开始录音
audioRecord.startRecording();
//子线程读取录音数据
private void writeDataTOFile() {
//缓冲区
byte[] bytes = new byte[bufferSizeInBytes];
FileOutputStream fos = null;
int readsize = 0;
try {
// fileName 为 .pcm 文件
String currentFileName = fileName;
File file = new File(currentFileName);
if (file.exists()) {
file.delete();
}
fos = new FileOutputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
recordStatus = AudioRecordStatus.STATUS_START;
Log.d(TAG,"开始录音...");
while (recordStatus == AudioRecordStatus.STATUS_START) {
readsize = audioRecord.read(bytes,0,bufferSizeInBytes);
if (AudioRecord.ERROR_INVALID_OPERATION != readsize && fos != null) {
try {
fos.write(bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// 停止录音
audioRecord.stop();
// 资源释放
audioRecord.release();

录音后的文件为 pcm 文件,需要再次转为 wav 文件。

参考文件

AudioRecord

Android 音视频深入