Android音视频开发之音频录制和播放

news/2024/11/24 9:06:35/

1.封装音频录制工具类:

public class RecorderAudioManagerUtils {private static volatile RecorderAudioManagerUtils mInstance;public static RecorderAudioManagerUtils getInstance() {if (mInstance == null) {synchronized (RecorderAudioManagerUtils.class) {if (mInstance == null) {mInstance = new RecorderAudioManagerUtils();}}}return mInstance;}}

2.音频录制方法:

    public void startRecord(WeakReference<Context> weakReference) {this.weakReference = weakReference;Log.e(TAG, "开始录音");//生成PCM文件String fileName = DateFormat.format("yyyy-MMdd-HHmmss", Calendar.getInstance(Locale.getDefault())) + ".pcm";File file = new File(Environment.getExternalStorageDirectory(), "/ACC音频/");if (!file.exists()) {file.mkdir();}String audioSaveDir = file.getAbsolutePath();Log.e(TAG, audioSaveDir);recordFile = new File(audioSaveDir, fileName);Log.e(TAG, "生成文件" + recordFile);//如果存在,就先删除再创建if (recordFile.exists()) {recordFile.delete();Log.e(TAG, "删除文件");}try {recordFile.createNewFile();Log.e(TAG, "创建文件");} catch (IOException e) {Log.e(TAG, "未能创建");throw new IllegalStateException("未能创建" + recordFile.toString());}if (filePathList.size() == 2) {filePathList.clear();}filePathList.add(recordFile);try {//输出流OutputStream os = new FileOutputStream(recordFile);BufferedOutputStream bos = new BufferedOutputStream(os);DataOutputStream dos = new DataOutputStream(bos);int bufferSize = AudioRecord.getMinBufferSize(sampleRateInHz, AudioFormat.CHANNEL_IN_STEREO, audioEncoding);if (ActivityCompat.checkSelfPermission(weakReference.get(), Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
​return;}audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, sampleRateInHz, AudioFormat.CHANNEL_IN_STEREO, audioEncoding, bufferSize);
​short[] buffer = new short[bufferSize];audioRecord.startRecording();Log.e(TAG, "开始录音");isRecording = true;while (isRecording) {int bufferReadResult = audioRecord.read(buffer, 0, bufferSize);for (int i = 0; i < bufferReadResult; i++) {dos.writeShort(buffer[i]);}}audioRecord.stop();dos.close();} catch (Exception e) {e.printStackTrace();Log.e(TAG, "录音失败");showToast("录音失败");}}

3.播放音频方法:

public void playPcm(boolean isChecked) {try {if (isChecked) {//两首一起播放for (File recordFiles : filePathList) {threadPoolExecutor.execute(() -> playPcmData(recordFiles));}} else {//只播放最后一次录音playPcmData(recordFile);}}catch (Exception e){e.printStackTrace();}
}

4.播放pcm流边录边播:

/*** 播放Pcm流,边读取边播*/
public void playPcmData(File recordFiles) {Log.e(TAG, "打印线程" + Thread.currentThread().getName());try {DataInputStream dis = new DataInputStream(new BufferedInputStream(new FileInputStream(recordFiles)));//最小缓存区int bufferSizeInBytes = AudioTrack.getMinBufferSize(sampleRateInHz, AudioFormat.CHANNEL_OUT_STEREO, audioEncoding);AudioTrack player = new AudioTrack(AudioManager.STREAM_MUSIC, sampleRateInHz, AudioFormat.CHANNEL_OUT_STEREO, audioEncoding, bufferSizeInBytes, AudioTrack.MODE_STREAM);short[] data = new short[bufferSizeInBytes];//开始播放player.play();while (true) {int i = 0;while (dis.available() > 0 && i < data.length) {data[i] = dis.readShort();i++;}player.write(data, 0, data.length);//表示读取完了if (i != bufferSizeInBytes) {player.stop();//停止播放player.release();//释放资源dis.close();showToast("播放完成了!!!");break;}}} catch (Exception e) {Log.e(TAG, "播放异常: " + e.getMessage());showToast("播放异常!!!!");e.printStackTrace();}
}

5.播放所有音频方法:

    public void playAllRecord() {if (recordFile == null) {return;}//读取文件int musicLength = (int) (recordFile.length() / 2);short[] music = new short[musicLength];try {InputStream is = new FileInputStream(recordFile);BufferedInputStream bis = new BufferedInputStream(is);DataInputStream dis = new DataInputStream(bis);int i = 0;while (dis.available() > 0) {music[i] = dis.readShort();i++;}dis.close();AudioTrack audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, sampleRateInHz, channelConfiguration, audioEncoding, musicLength * 2, AudioTrack.MODE_STREAM);audioTrack.play();audioTrack.write(music, 0, musicLength);audioTrack.stop();} catch (Throwable t) {Log.e(TAG, "播放失败");showToast("播放失败");}}

如需完整版 Android 音视频从入门到高级进阶学习笔记 请点击此处免费领取

6.设置是否录音方法:

public void setRecord(boolean isRecording) {this.isRecording = isRecording;
}

7.暂停播放音频方法:

    public void pauseAudio(){if(audioRecord != null ){audioRecord.stop();}}

8.回收资源和播放器方法:

    public void releaseAudio(){if(audioRecord != null){audioRecord.release();}if(handler != null){handler.removeCallbacksAndMessages(null);}if(threadPoolExecutor != null){threadPoolExecutor.shutdown();}}

9.音频播放、文件读写权限申请:

    private void afterPermissions() {// Marshmallow开始才用申请运行时权限if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {for (int i = 0; i < permissions.length; i++) {if (ContextCompat.checkSelfPermission(this, permissions[i]) !=PackageManager.PERMISSION_GRANTED) {mPermissionList.add(permissions[i]);}}if (!mPermissionList.isEmpty()) {String[] permissions = mPermissionList.toArray(new String[mPermissionList.size()]);ActivityCompat.requestPermissions(this, permissions, MY_PERMISSIONS_REQUEST);}}}

10.调用开始录音:

       btnRecord.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {buttonEnabled(false, true, true);Toast.makeText(MainActivity.this, "开始录音", Toast.LENGTH_SHORT).show();threadPoolExecutor.execute(() -> {RecorderAudioManagerUtils.getInstance().startRecord(new WeakReference<>(getApplicationContext()));});}});

11.调用播放音频:

       btnPlay.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {RecorderAudioManagerUtils.getInstance().playPcm(true);buttonEnabled(false, false, true);}});

12.调用停止录音:

        btnStop.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {new Handler().post(new Runnable() {@Overridepublic void run() {buttonEnabled(true, true, false);Toast.makeText(MainActivity.this, "停止录音", Toast.LENGTH_SHORT).show();RecorderAudioManagerUtils.getInstance().pauseAudio();}});}});

13.设置录音、播放、停止按钮状态:

private void buttonEnabled(boolean record, boolean play, boolean stop) {btnRecord.setEnabled(record);btnPlay.setEnabled(play);btnStop.setEnabled(stop);
}

14.布局文件代码如下:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"tools:context=".MainActivity"><Buttonandroid:id="@+id/btn_record"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="录制音频"app:layout_constraintBottom_toBottomOf="parent"app:layout_constraintEnd_toStartOf="@id/btn_play"app:layout_constraintStart_toStartOf="parent"app:layout_constraintTop_toTopOf="parent" /><Buttonandroid:id="@+id/btn_play"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="播放音频"app:layout_constraintBottom_toBottomOf="parent"app:layout_constraintEnd_toStartOf="@id/btn_stop"app:layout_constraintStart_toEndOf="@id/btn_record"app:layout_constraintTop_toTopOf="parent" /><Buttonandroid:id="@+id/btn_stop"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="停止录制"app:layout_constraintBottom_toBottomOf="parent"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintStart_toEndOf="@id/btn_play"app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

15.布局预览效果如下:

在这里插入图片描述

在这里插入图片描述

16.完整MainActivity代码:

public class MainActivity extends AppCompatActivity {private Button btnRecord,btnPlay,btnStop;ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(3, 5,1, TimeUnit.MINUTES,new LinkedBlockingDeque<>(10),Executors.defaultThreadFactory(),new ThreadPoolExecutor.AbortPolicy());private String[] permissions = new String[]{android.Manifest.permission.RECORD_AUDIO,Manifest.permission.WRITE_EXTERNAL_STORAGE};/*** 被用户拒绝的权限列表*/private List<String> mPermissionList = new ArrayList<>();private static final int MY_PERMISSIONS_REQUEST = 1001;private final String TAG = MainActivity.this.getClass().getSimpleName();@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);afterPermissions();initView();}private void afterPermissions() {// Marshmallow开始才用申请运行时权限if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {for (int i = 0; i < permissions.length; i++) {if (ContextCompat.checkSelfPermission(this, permissions[i]) !=PackageManager.PERMISSION_GRANTED) {mPermissionList.add(permissions[i]);}}if (!mPermissionList.isEmpty()) {String[] permissions = mPermissionList.toArray(new String[mPermissionList.size()]);ActivityCompat.requestPermissions(this, permissions, MY_PERMISSIONS_REQUEST);}}}private void initView() {btnRecord = findViewById(R.id.btn_record);btnPlay = findViewById(R.id.btn_play);btnStop = findViewById(R.id.btn_stop);btnRecord.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {buttonEnabled(false, true, true);Toast.makeText(MainActivity.this, "开始录音", Toast.LENGTH_SHORT).show();threadPoolExecutor.execute(() -> {RecorderAudioManagerUtils.getInstance().startRecord(new WeakReference<>(getApplicationContext()));});}});btnPlay.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {RecorderAudioManagerUtils.getInstance().playPcm(true);buttonEnabled(false, false, true);}});btnStop.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {new Handler().post(new Runnable() {@Overridepublic void run() {buttonEnabled(true, true, false);Toast.makeText(MainActivity.this, "停止录音", Toast.LENGTH_SHORT).show();RecorderAudioManagerUtils.getInstance().pauseAudio();}});}});}private void buttonEnabled(boolean record, boolean play, boolean stop) {btnRecord.setEnabled(record);btnPlay.setEnabled(play);btnStop.setEnabled(stop);}@Overrideprotected void onStop() {super.onStop();RecorderAudioManagerUtils.getInstance().pauseAudio();}@Overrideprotected void onDestroy() {super.onDestroy();RecorderAudioManagerUtils.getInstance().releaseAudio();}@Overridepublic void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {super.onRequestPermissionsResult(requestCode, permissions, grantResults);boolean allGranted = true;for (int results : grantResults) {allGranted &= results == PackageManager.PERMISSION_GRANTED;}if (allGranted) {afterPermissions();} else {Toast.makeText(this, "请打开特殊权限", Toast.LENGTH_LONG).show();}}}

17.工具类完整代码如下:

package com.example.audiorecorddemo.utils;import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioRecord;
import android.media.AudioTrack;
import android.media.MediaRecorder;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.text.format.DateFormat;
import android.util.Log;
import android.widget.Toast;import androidx.core.app.ActivityCompat;import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;/*** @author: njb* @date: 2023/2/25 18:29* @desc:*/
public class RecorderAudioManagerUtils {private static final String TAG = "PlayManagerUtils";private WeakReference<Context> weakReference;private File recordFile;private boolean isRecording;/*** 最多只能存2条记录*/private final List<File> filePathList = new ArrayList<>(2);/*** 16K采集率*/int sampleRateInHz = 16000;/*** 格式*/int channelConfiguration = AudioFormat.CHANNEL_OUT_STEREO;/*** 16Bit*/int audioEncoding = AudioFormat.ENCODING_PCM_16BIT;private static volatile RecorderAudioManagerUtils mInstance;private final Handler handler = new Handler(Looper.getMainLooper());AudioRecord audioRecord;ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(3, 5, 1, TimeUnit.MINUTES, new LinkedBlockingDeque<>(10));public static RecorderAudioManagerUtils getInstance() {if (mInstance == null) {synchronized (RecorderAudioManagerUtils.class) {if (mInstance == null) {mInstance = new RecorderAudioManagerUtils();}}}return mInstance;}public void startRecord(WeakReference<Context> weakReference) {this.weakReference = weakReference;Log.e(TAG, "开始录音");//生成PCM文件String fileName = DateFormat.format("yyyy-MMdd-HHmmss", Calendar.getInstance(Locale.getDefault())) + ".pcm";File file = new File(Environment.getExternalStorageDirectory(), "/ACC音频/");if (!file.exists()) {file.mkdir();}String audioSaveDir = file.getAbsolutePath();Log.e(TAG, audioSaveDir);recordFile = new File(audioSaveDir, fileName);Log.e(TAG, "生成文件" + recordFile);//如果存在,就先删除再创建if (recordFile.exists()) {recordFile.delete();Log.e(TAG, "删除文件");}try {recordFile.createNewFile();Log.e(TAG, "创建文件");} catch (IOException e) {Log.e(TAG, "未能创建");throw new IllegalStateException("未能创建" + recordFile.toString());}if (filePathList.size() == 2) {filePathList.clear();}filePathList.add(recordFile);try {//输出流OutputStream os = new FileOutputStream(recordFile);BufferedOutputStream bos = new BufferedOutputStream(os);DataOutputStream dos = new DataOutputStream(bos);int bufferSize = AudioRecord.getMinBufferSize(sampleRateInHz, AudioFormat.CHANNEL_IN_STEREO, audioEncoding);if (ActivityCompat.checkSelfPermission(weakReference.get(), Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {return;}audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, sampleRateInHz, AudioFormat.CHANNEL_IN_STEREO, audioEncoding, bufferSize);short[] buffer = new short[bufferSize];audioRecord.startRecording();Log.e(TAG, "开始录音");isRecording = true;while (isRecording) {int bufferReadResult = audioRecord.read(buffer, 0, bufferSize);for (int i = 0; i < bufferReadResult; i++) {dos.writeShort(buffer[i]);}}audioRecord.stop();dos.close();} catch (Exception e) {e.printStackTrace();Log.e(TAG, "录音失败");showToast("录音失败");}}/*** 播放pcm流的方法,一次性读取所有Pcm流,读完后在开始播放*/public void playAllRecord() {if (recordFile == null) {return;}//读取文件int musicLength = (int) (recordFile.length() / 2);short[] music = new short[musicLength];try {InputStream is = new FileInputStream(recordFile);BufferedInputStream bis = new BufferedInputStream(is);DataInputStream dis = new DataInputStream(bis);int i = 0;while (dis.available() > 0) {music[i] = dis.readShort();i++;}dis.close();AudioTrack audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, sampleRateInHz, channelConfiguration, audioEncoding, musicLength * 2, AudioTrack.MODE_STREAM);audioTrack.play();audioTrack.write(music, 0, musicLength);audioTrack.stop();} catch (Throwable t) {Log.e(TAG, "播放失败");showToast("播放失败");}}public void playPcm(boolean isChecked) {try {if (isChecked) {//两首一起播放for (File recordFiles : filePathList) {threadPoolExecutor.execute(() -> playPcmData(recordFiles));}} else {//只播放最后一次录音playPcmData(recordFile);}}catch (Exception e){e.printStackTrace();}}/*** 播放Pcm流,边读取边播*/public void playPcmData(File recordFiles) {Log.e(TAG, "打印线程" + Thread.currentThread().getName());try {DataInputStream dis = new DataInputStream(new BufferedInputStream(new FileInputStream(recordFiles)));//最小缓存区int bufferSizeInBytes = AudioTrack.getMinBufferSize(sampleRateInHz, AudioFormat.CHANNEL_OUT_STEREO, audioEncoding);AudioTrack player = new AudioTrack(AudioManager.STREAM_MUSIC, sampleRateInHz, AudioFormat.CHANNEL_OUT_STEREO, audioEncoding, bufferSizeInBytes, AudioTrack.MODE_STREAM);short[] data = new short[bufferSizeInBytes];//开始播放player.play();while (true) {int i = 0;while (dis.available() > 0 && i < data.length) {data[i] = dis.readShort();i++;}player.write(data, 0, data.length);//表示读取完了if (i != bufferSizeInBytes) {player.stop();//停止播放player.release();//释放资源dis.close();showToast("播放完成了!!!");break;}}} catch (Exception e) {Log.e(TAG, "播放异常: " + e.getMessage());showToast("播放异常!!!!");e.printStackTrace();}}public File getRecordFile() {return recordFile;}public void setRecord(boolean isRecording) {this.isRecording = isRecording;}public void pauseAudio(){if(audioRecord != null ){audioRecord.stop();}}public void releaseAudio(){if(audioRecord != null){audioRecord.release();}if(handler != null){handler.removeCallbacksAndMessages(null);}if(threadPoolExecutor != null){threadPoolExecutor.shutdown();}}private void showToast(String msg) {if(weakReference.get() != null){handler.post(() -> Toast.makeText(weakReference.get(), msg, Toast.LENGTH_LONG).show());}}}

http://www.ppmy.cn/news/63624.html

相关文章

mysql从零开始(05)----锁

全局锁 使用 # 启用全局锁 flush tables with read lock # 释放全局锁 unlock tables开启全局锁后&#xff0c;整个数据库就处于只读状态了&#xff0c;这种状态下&#xff0c;对数据的增删改操作、对表结构的更改操作都会被阻塞。 另外&#xff0c;当会话断开&#xff0c;全…

接口自动化测试的神器:使用Python编写高效的自动化测试工具

B站首推&#xff01;2023最详细自动化测试合集&#xff0c;小白皆可掌握&#xff0c;让测试变得简单、快捷、可靠https://www.bilibili.com/video/BV1ua4y1V7Db 目录 摘要&#xff1a; 安装工具&#xff1a; 测试脚本 编写python脚本 1.使用requests发送HTTP请求 2.使用py…

通俗理解CNN感受野的计算方法

x o u t x i n − k s 1 x_{out} \frac{x_{in} - k}{s} 1 xout​sxin​−k​1 如果不考虑padding&#xff0c;卷积输出的feature map的计算公式如上&#xff0c;那么 x i n ( x o u t − 1 ) ∗ s k x_{in} (x_{out} - 1) * s k xin​(xout​−1)∗sk。因此计算模型的感…

APP外包项目的线上维护方案

APP的使用已经非常普及&#xff0c;不论是2C还是2B的APP都已经渗透到了我们生活的方方面面&#xff0c;对于APP的开发公司来说APP项目的线上维护是一个非常重要的问题。如果APP项目比较重要而且用户规模比较大&#xff0c;那更需要专业的技术团队来维护。今天和大家分享这方面的…

[LeetCode周赛复盘] 第 344 场周赛20230507

[LeetCode周赛复盘] 第 344 场周赛20230507 一、本周周赛总结6416. 找出不同元素数目差数组1. 题目描述2. 思路分析3. 代码实现 6417. 频率跟踪器1. 题目描述2. 思路分析3. 代码实现 6418. 有相同颜色的相邻元素数目1. 题目描述2. 思路分析3. 代码实现 6419. 使二叉树所有路径…

Qt5.9学习笔记-事件(四)Qt5.9中常见事件

⭐️我叫忆_恒心&#xff0c;一名喜欢书写博客的在读研究生&#x1f468;‍&#x1f393;。 如果觉得本文能帮到您&#xff0c;麻烦点个赞&#x1f44d;呗&#xff01; 近期会不断在专栏里进行更新讲解博客~~~ 有什么问题的小伙伴 欢迎留言提问欧&#xff0c;喜欢的小伙伴给个三…

聚焦丨酷雷曼荣列XRMA联盟成员单位

自“元宇宙”概念兴起之初&#xff0c;酷雷曼VR所属北京同创蓝天云科技有限公司就积极布局、探索和实践。2022年12月&#xff0c;酷雷曼VR成功加入虚拟现实与元宇宙产业联盟&#xff08;XRMA&#xff09;&#xff0c;正式被接纳为联盟成员单位&#xff0c;意味着酷雷曼公司将进…

Stream

1、Stream为什么被引入 常见MQ(消息中间件)&#xff1a; ActiveMQRabbitMQRocketMQKafka 有没有一种新的技术诞生&#xff0c;让我们不再关注具体MQ的细节&#xff0c;我们只需要用一种适配绑定的方式&#xff0c;自动的给我们在各种MQ内切换。&#xff08;类似于Hibernate&a…