本文主要是介绍Android音视频任务列表之(二)——在 Android 平台使用 AudioRecord 和 AudioTrack API 完成音频 PCM 数据的采集和播放,并实现读写音频 wav 文件,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一.主要使用方法
1.获取缓存大小
AudioRecord.getMinBufferSize(int sampleRateInHz, int channelConfig, int audioFormat)
参数:
sampleRateInHz:采样率
channelConfig:通道组(单通道,双通道)
audioFormat:音频数据的格式
2.创建录音对象
AudioRecord(int audioSource, int sampleRateInHz, int channelConfig, int audioFormat,
int bufferSizeInBytes)
参数:
audioSource: 音频源
sampleRateInHz :采样率
channelConfig:音频通道
audioFormat:返回音频数据的格式。
bufferSizeInBytes:写入音频数据的缓冲区的大小
3.开始录音
audioRecord.startRecording()
4.获取录音数据
audioRecord.read(@NonNull byte[] audioData, int offsetInBytes, int sizeInBytes)
参数:
audioData:记录音频数据的数组
offsetInBytes:开始索引
sizeInBytes:数据大小
5.开始播放
audioTrack.play()
二.实现过程
1.申请权限:RECORD_AUDIO,READ_EXTERNAL_STORAGE,WRITE_EXTERNAL_STORAGE
2.开始录音
// 音频来源:麦克风private final static int AUDIO_INPUT = MediaRecorder.AudioSource.MIC;// 采样率// 采样频率一般共分为22.05KHz、44.1KHz、48KHz三个等级private final static int AUDIO_SAMPLE_RATE = 44100;// 音频通道 单声道private final static int AUDIO_CHANNEL = AudioFormat.CHANNEL_IN_STEREO;// 音频格式:PCM编码private final static int AUDIO_ENCODING = AudioFormat.ENCODING_PCM_16BIT;private final String pcmFileName = Environment.getExternalStorageDirectory() + "/record.pcm";private final String wavFileName = Environment.getExternalStorageDirectory() + "/record.wav";private AudioRecord audioRecord = null;private int recordBufSize = 0; // 声明recoordBufffer的大小字段private byte[] buffer;private boolean isRecording;private void start(){//audioRecord能接受的最小的buffer大小recordBufSize = AudioRecord.getMinBufferSize(AUDIO_SAMPLE_RATE, AUDIO_CHANNEL, AUDIO_ENCODING);audioRecord = new AudioRecord(AUDIO_INPUT, AUDIO_SAMPLE_RATE, AUDIO_CHANNEL, AUDIO_ENCODING, recordBufSize);buffer = new byte[recordBufSize];//开始录音audioRecord.startRecording();isRecording = true;new Thread(() -> {FileOutputStream os = null;try {File pcmFile= new File(pcmFileName);if(!pcmFile.exists()){pcmFile.createNewFile();}os = new FileOutputStream(pcmFileName);} catch (Exception e) {e.printStackTrace();}if (null != os) {while (isRecording) {int read = audioRecord.read(buffer, 0, recordBufSize);// 如果读取音频数据没有出现错误,就将数据写入到文件if (AudioRecord.ERROR_INVALID_OPERATION != read) {try {os.write(buffer);} catch (IOException e) {e.printStackTrace();}}}try {os.close();} catch (IOException e) {e.printStackTrace();}}}).start();}
3.停止录音
private void stop(){isRecording = false;if (null != audioRecord) {audioRecord.stop();audioRecord.release();audioRecord = null;}}
4.播放PCM文件
private void play(){Toast.makeText(this,"开始播放",Toast.LENGTH_LONG).show();int channelConfig = AudioFormat.CHANNEL_OUT_MONO;audioTrack = new AudioTrack(new AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_MEDIA).setContentType(AudioAttributes.CONTENT_TYPE_MUSIC).build(),new AudioFormat.Builder().setSampleRate(44100).setEncoding(AUDIO_ENCODING).setChannelMask(channelConfig).build(),recordBufSize,AudioTrack.MODE_STREAM,AudioManager.AUDIO_SESSION_ID_GENERATE);audioTrack.play();File file = new File(pcmFileName);try {FileInputStream fileInputStream = new FileInputStream(file);new Thread(new Runnable() {@Overridepublic void run() {try {byte[] tempBuffer = new byte[recordBufSize];while (fileInputStream.available() > 0) {int readCount = fileInputStream.read(tempBuffer);if (readCount == AudioTrack.ERROR_INVALID_OPERATION ||readCount == AudioTrack.ERROR_BAD_VALUE) {continue;}if (readCount != 0 && readCount != -1) {audioTrack.write(tempBuffer, 0, readCount);}}} catch (IOException e) {e.printStackTrace();}}}).start();} catch (IOException e) {e.printStackTrace();}}
5.PCM转WAV
Pcm2WavUtil.pcmToWav(AUDIO_SAMPLE_RATE, AUDIO_CHANNEL,recordBufSize, pcmFileName, wavFileName);
6.Pcm2WavUtil工具类
public class Pcm2WavUtil {/*** pcm文件转wav文件* @param inFilename 源文件路径* @param outFilename 目标文件路径*/public static void pcmToWav(long mSampleRate, int mChannel, int mBufferSize, String inFilename, String outFilename) {FileInputStream in;FileOutputStream out;long totalAudioLen;long totalDataLen;long longSampleRate = mSampleRate;int channels = mChannel == AudioFormat.CHANNEL_IN_MONO ? 1 : 2;long byteRate = 16 * mSampleRate * channels / 8;byte[] data = new byte[mBufferSize];try {in = new FileInputStream(inFilename);out = new FileOutputStream(outFilename);totalAudioLen = in.getChannel().size();totalDataLen = totalAudioLen + 36;writeWaveFileHeader(out, totalAudioLen, totalDataLen,longSampleRate, channels, byteRate);while (in.read(data) != -1) {out.write(data);}in.close();out.close();} catch (IOException e) {e.printStackTrace();}}// 添加wav文件头private static void writeWaveFileHeader(FileOutputStream out, long totalAudioLen,long totalDataLen, long longSampleRate, int channels, long byteRate)throws IOException {byte[] header = new byte[44];header[0] = 'R';header[1] = 'I';header[2] = 'F';header[3] = 'F';header[4] = (byte) (totalDataLen & 0xff);header[5] = (byte) ((totalDataLen >> 8) & 0xff);header[6] = (byte) ((totalDataLen >> 16) & 0xff);header[7] = (byte) ((totalDataLen >> 24) & 0xff);header[8] = 'W';header[9] = 'A';header[10] = 'V';header[11] = 'E';header[12] = 'f';header[13] = 'm';header[14] = 't';header[15] = ' ';header[16] = 16;header[17] = 0;header[18] = 0;header[19] = 0;header[20] = 1;header[21] = 0;header[22] = (byte) channels;header[23] = 0;header[24] = (byte) (longSampleRate & 0xff);header[25] = (byte) ((longSampleRate >> 8) & 0xff);header[26] = (byte) ((longSampleRate >> 16) & 0xff);header[27] = (byte) ((longSampleRate >> 24) & 0xff);header[28] = (byte) (byteRate & 0xff);header[29] = (byte) ((byteRate >> 8) & 0xff);header[30] = (byte) ((byteRate >> 16) & 0xff);header[31] = (byte) ((byteRate >> 24) & 0xff);header[32] = (byte) (2 * 16 / 8);header[33] = 0;header[34] = 16;header[35] = 0;header[36] = 'd';header[37] = 'a';header[38] = 't';header[39] = 'a';header[40] = (byte) (totalAudioLen & 0xff);header[41] = (byte) ((totalAudioLen >> 8) & 0xff);header[42] = (byte) ((totalAudioLen >> 16) & 0xff);header[43] = (byte) ((totalAudioLen >> 24) & 0xff);out.write(header, 0, 44);}
}
三.最终效果
在外部存储根目录输出一个record.pcm文件和一个record.wav文件
这篇关于Android音视频任务列表之(二)——在 Android 平台使用 AudioRecord 和 AudioTrack API 完成音频 PCM 数据的采集和播放,并实现读写音频 wav 文件的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!