十年网站开发经验 + 多家企业客户 + 靠谱的建站团队
量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决
这篇文章将为大家详细讲解有关Android如何实现仿微信录音功能,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。
创新互联是一家专注于成都网站建设、网站建设与策划设计,内乡网站建设哪家好?创新互联做网站,专注于网站建设10余年,网设计领域的专业建站公司;建站业务涵盖:内乡等地区。内乡做网站价格咨询:13518219792
提要:需求是开发类似微信发语音的功能,没有语音转文字。网上看了一些代码,不能拿来直接用,部分代码逻辑有问题,所以想把自己的代码贴出来,仅供参考。
功能:
a、设置最大录音时长和录音倒计时(为了方便测试,最大时长设置为15秒,开始倒计时设置为7秒)
b、在录音之前检查录音和存储权限
源码:
1、录音对话框管理类DialogManager:
/** * 功能:录音对话框管理类 */public class DialogManager { private AlertDialog.Builder builder; private AlertDialog dialog; private ImageView mIcon; private ImageView mVoice; private TextView mLabel; private Context context; /** * 构造方法 * * @param context Activity级别的Context */ public DialogManager(Context context) { this.context = context; } /** * 显示录音的对话框 */ public void showRecordingDialog() { builder = new AlertDialog.Builder(context, R.style.AudioRecorderDialogStyle); LayoutInflater inflater = LayoutInflater.from(context); View view = inflater.inflate(R.layout.audio_recorder_dialog, null); mIcon = view.findViewById(R.id.iv_dialog_icon); mVoice = view.findViewById(R.id.iv_dialog_voice); mLabel = view.findViewById(R.id.tv_dialog_label); builder.setView(view); dialog = builder.create(); dialog.show(); dialog.setCanceledOnTouchOutside(false); } /** * 正在播放时的状态 */ public void recording() { if (dialog != null && dialog.isShowing()) { //显示状态 mIcon.setVisibility(View.VISIBLE); mVoice.setVisibility(View.VISIBLE); mLabel.setVisibility(View.VISIBLE); mIcon.setImageResource(R.drawable.ic_audio_recorder); mVoice.setImageResource(R.drawable.ic_audio_v1); mLabel.setText(R.string.audio_record_dialog_up_to_cancel); } } /** * 显示想取消的对话框 */ public void wantToCancel() { if (dialog != null && dialog.isShowing()) { //显示状态 mIcon.setVisibility(View.VISIBLE); mVoice.setVisibility(View.GONE); mLabel.setVisibility(View.VISIBLE); mIcon.setImageResource(R.drawable.ic_audio_cancel); mLabel.setText(R.string.audio_record_dialog_release_to_cancel); } } /** * 显示时间过短的对话框 */ public void tooShort() { if (dialog != null && dialog.isShowing()) { //显示状态 mIcon.setVisibility(View.VISIBLE); mVoice.setVisibility(View.GONE); mLabel.setVisibility(View.VISIBLE); mLabel.setText(R.string.audio_record_dialog_too_short); } } // 显示取消的对话框 public void dismissDialog() { if (dialog != null && dialog.isShowing()) { //显示状态 dialog.dismiss(); dialog = null; } } /** * 显示更新音量级别的对话框 * * @param level 1-7 */ public void updateVoiceLevel(int level) { if (dialog != null && dialog.isShowing()) { //显示状态 mIcon.setVisibility(View.VISIBLE); mVoice.setVisibility(View.VISIBLE); mLabel.setVisibility(View.VISIBLE); int resId = context.getResources().getIdentifier("ic_audio_v" + level, "drawable", context.getPackageName()); mVoice.setImageResource(resId); } } public void updateTime(int time) { if (dialog != null && dialog.isShowing()) { //显示状态 mIcon.setVisibility(View.VISIBLE); mVoice.setVisibility(View.VISIBLE); mLabel.setVisibility(View.VISIBLE); mLabel.setText(time + "s"); } }}
2、录音管理类AudioManager
/** * 功能:录音管理类 */public class AudioManager { private MediaRecorder mMediaRecorder; private String mDir; private String mCurrentFilePath; private static AudioManager mInstance; private boolean isPrepared; private AudioManager(String dir) { this.mDir = dir; } //单例模式:在这里实例化AudioManager并传入录音文件地址 public static AudioManager getInstance(String dir) { if (mInstance == null) { synchronized (AudioManager.class) { if (mInstance == null) { mInstance = new AudioManager(dir); } } } return mInstance; } /** * 回调准备完毕 */ public interface AudioStateListener { void wellPrepared(); } public AudioStateListener mListener; /** * 回调方法 */ public void setOnAudioStateListener(AudioStateListener listener) { mListener = listener; } /** * 准备 */ public void prepareAudio() { try { isPrepared = false; File dir = FileUtils.createNewFile(mDir); String fileName = generateFileName(); File file = new File(dir, fileName); mCurrentFilePath = file.getAbsolutePath(); Logger.t("AudioManager").i("audio file name :" + mCurrentFilePath); mMediaRecorder = new MediaRecorder(); //设置输出文件 mMediaRecorder.setOutputFile(mCurrentFilePath); //设置MediaRecorder的音频源为麦克风 mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); //设置音频格式 mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4); //设置音频的格式为AAC mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC); //准备录音 mMediaRecorder.prepare(); //开始 mMediaRecorder.start(); //准备结束 isPrepared = true; if (mListener != null) { mListener.wellPrepared(); } } catch (Exception e) { e.printStackTrace(); } } /** * 随机生成文件的名称 */ private String generateFileName() { return UUID.randomUUID().toString() + ".m4a"; } public int getVoiceLevel(int maxLevel) { if (isPrepared) { try { //获得最大的振幅getMaxAmplitude() 1-32767 return maxLevel * mMediaRecorder.getMaxAmplitude() / 32768 + 1; } catch (Exception e) { } } return 1; } /** * 释放资源 */ public void release() { if (mMediaRecorder != null) { mMediaRecorder.stop(); mMediaRecorder.release(); mMediaRecorder = null; } } public void cancel() { release(); if (mCurrentFilePath != null) { File file = new File(mCurrentFilePath); FileUtils.deleteFile(file); mCurrentFilePath = null; } } public String getCurrentFilePath() { return mCurrentFilePath; }}
3、自定义录音按钮AudioRecorderButton
/** * 功能:录音按钮 */public class AudioRecorderButton extends AppCompatButton { private Context mContext; //取消录音Y轴位移 private static final int DISTANCE_Y_CANCEL = 80; //录音最大时长限制 private static final int AUDIO_RECORDER_MAX_TIME = 15; //录音倒计时时间 private static final int AUDIO_RECORDER_COUNT_DOWN = 7; //状态 private static final int STATE_NORMAL = 1;// 默认的状态 private static final int STATE_RECORDING = 2;// 正在录音 private static final int STATE_WANT_TO_CANCEL = 3;// 希望取消 //当前的状态 private int mCurrentState = STATE_NORMAL; //已经开始录音 private boolean isRecording = false; //是否触发onLongClick private boolean mReady; private DialogManager mDialogManager; private AudioManager mAudioManager; private android.media.AudioManager audioManager; public AudioRecorderButton(Context context) { this(context, null); } public AudioRecorderButton(Context context, AttributeSet attrs) { super(context, attrs); this.mContext = context; mDialogManager = new DialogManager(context); audioManager = (android.media.AudioManager) context.getSystemService(Context.AUDIO_SERVICE); String dir = SdUtils.getCustomFolder("Audios");//创建文件夹 mAudioManager = AudioManager.getInstance(dir); mAudioManager.setOnAudioStateListener(new AudioManager.AudioStateListener() { @Override public void wellPrepared() { mHandler.sendEmptyMessage(MSG_AUDIO_PREPARED); } }); //按钮长按 准备录音 包括start setOnLongClickListener(new OnLongClickListener() { @Override public boolean onLongClick(View v) { //先判断有没有录音和存储权限,有则开始录音,没有就申请权限 int hasAudioPermission = ContextCompat.checkSelfPermission(mContext, Manifest.permission.RECORD_AUDIO); int hasStoragePermission = ContextCompat.checkSelfPermission(mContext, Manifest.permission.WRITE_EXTERNAL_STORAGE); if (hasAudioPermission == PackageManager.PERMISSION_GRANTED && hasStoragePermission == PackageManager.PERMISSION_GRANTED) { mReady = true; mAudioManager.prepareAudio(); } else { RxPermissions permissions = new RxPermissions((FragmentActivity) mContext); Disposable disposable = permissions.request(Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE) .subscribe(new Consumer
4、DialogStyle
5、DialogLayout
6、用到的字符串
7、使用:按钮的样式不需要写在自定义Button中,方便使用
关于“Android如何实现仿微信录音功能”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。