一.AudioRecord 和 AudioTrack
AudioRecord:Android平台用于录制音频的类。
AudioTrack:Android平台用于播放音频的类。
二.AudioRecord 和 AudioTrack构造方法
AudioRecord音频采集
Public constructors
<init>(audioSource: Int, sampleRateInHz: Int, channelConfig: Int, audioFormat: Int, bufferSizeInBytes: Int)
- audioSource:音频源
- sampleRateInHz:采样频率
- channelConfig:音频通道,单声道,双声道,立体声。
- audioFormat:音频数据源格式
- bufferSizeInBytes:音频数据缓存总大小
AudioTrack音频播放
@param streamType the type of the audio stream. See
* {@link AudioManager#STREAM_VOICE_CALL}, {@link AudioManager#STREAM_SYSTEM},
* {@link AudioManager#STREAM_RING}, {@link AudioManager#STREAM_MUSIC},
* {@link AudioManager#STREAM_ALARM}, and {@link AudioManager#STREAM_NOTIFICATION}.
Public constructors
<init>(streamType: Int, sampleRateInHz: Int, channelConfig: Int, audioFormat: Int, bufferSizeInBytes: Int, mode: Int)
- streamType:音频流数据类型,类型如下:
- STREAM_VOICE_CALL:电话
- STREAM_SYSTEM:系统
- STREAM_RING:铃声
- STREAM_MUSIC:音乐
- STREAM_ALARM:闹钟
- STREAM_NOTIFICATION:通知
三.AudioRecord 和 AudioTrack使用
- AudioRecord
- AudioRecord初始化:
int bufferSizeInBytes = AudioRecord.getMinBufferSize(SAMPLE_RATE_INHZ, CHANNEL_CONFIG, AUDIO_FORMAT);
audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, SAMPLE_RATE_INHZ,
CHANNEL_CONFIG, AUDIO_FORMAT, bufferSizeInBytes);
- 获取音频数据并写入文件:
final byte data[] = new byte[bufferSizeInBytes];
final File file = new File(getExternalFilesDir(Environment.DIRECTORY_MUSIC), "record.pcm");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
while (isRecording) {
int read = audioRecord.read(data, 0, data.length);
if (AudioRecord.ERROR_INVALID_OPERATION != read) {
fos.write(data);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
- AudioTrack
- AudioTrack初始化:
audioTrack = new AudioTrack(
new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_MEDIA)
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.build(),
new AudioFormat.Builder().setSampleRate(SAMPLE_RATE_INHZ)
.setEncoding(AUDIO_FORMAT)
.setChannelMask(AudioFormat.CHANNEL_OUT_MONO)
.build(),
bufferSizeInBytes,
AudioTrack.MODE_STREAM,
AudioManager.AUDIO_SESSION_ID_GENERATE);
audioTrack.play();
- AudioTrack读取数据并写入: <