一、前言:長按錄音不算太常見功能漆腌,萬一你剛好需要呢贼邓。
二、效果圖:
三闷尿、解決思路
主要用的是MediaRecorder塑径,可能你百度MediaRecorder,就知道怎么做了填具,不過有些細(xì)節(jié)需要自己處理统舀。
四、給長按的全部代碼
private val mOnVoiceBtnTouchListener =
OnTouchListener { v, event ->
if (mBinding.tvClickPlay.visibility == View.VISIBLE){
return@OnTouchListener false
}
val mOffsetLimit = 70 * v.context.resources.displayMetrics.density
//val permissions = arrayOf(Manifest.permission.RECORD_AUDIO)
if (!PermissionCheckUtil.checkPermissions(v.context, PermissionAppUtils.Group.RECORD_AUDIO_STORAGE)
&& event.action == MotionEvent.ACTION_DOWN
) {
DialogUtils.okAndCancel(mContext, getString(R.string.record_audio_permission_tip) , ok = getString(R.string.go_open), okListener = {
PermissionAppUtils.requestCombinedPermission(mContext,
PermissionAppUtils.Group.RECORD_AUDIO_STORAGE) {
if (it.granted){
} else {
if (it.shouldShowRequestPermissionRationale){
//禁止,不做操作
} else {
//永久禁止,需求說只彈前面的彈框劳景,永久禁止就直接跳設(shè)置
CUtils.startAppSettings(mContext)
}
}
}
})
return@OnTouchListener true
}
if (event.action == MotionEvent.ACTION_DOWN) {
if (MyAudioPlayManager.getInstance().isPlaying) {
MyAudioPlayManager.getInstance().stopPlay()
}
// 判斷正在視頻通話和語音通話中不能進(jìn)行語音錄制
if (EasyFloat.appFloatIsShow(SingleCallActivity.video_float_tag) || EasyFloat.appFloatIsShow(SingleCallActivity.audio_float_tag)
|| ActivityUtil.isActivityExist(SingleCallActivity::class.java)) {
mContext.show(R.string.rc_voip_occupying)
return@OnTouchListener true
}
mBinding.ivStartRecordAudio.setImageResource(R.mipmap.ic_record_audio_press)
//開始錄音,錄之前先刪掉之前的本地錄的
MyAudioRecordManager.getInstance().deleteAudioFile()
currentRecordTime = 0
isStartRecording = true
MyAudioRecordManager.getInstance().startRec(mContext)
mLastTouchY = event.y
mUpDirection = false
if (disposableRecordTime == null || disposableRecordTime!!.isDisposed){
disposableRecordTime = Observable.interval(1,TimeUnit.SECONDS,AndroidSchedulers.mainThread())
.take(recordMaxTime)
.subscribe{
Log.i("currentRecordTime",it.toString())
currentRecordTime = it+1
dealCurrentTimeShow(currentRecordTime,true)
//錄夠15s停止錄制
if (currentRecordTime == recordMaxTime){
MyAudioRecordManager.getInstance().stopRec()
showRecordAfter()
}
}
}
} else if (event.action == MotionEvent.ACTION_MOVE) {
mBinding.ivStartRecordAudio.setImageResource(R.mipmap.ic_record_audio_press)
} else if (event.action == MotionEvent.ACTION_UP || event.action == MotionEvent.ACTION_CANCEL) {
mBinding.ivStartRecordAudio.setImageResource(R.mipmap.ic_record_audio)
//松手停止錄制
if (isStartRecording){
MyAudioRecordManager.getInstance().stopRec()
if (currentRecordTime < 3){
show(R.string.record_audio_not_enough_tip)
currentRecordTime = 0
dealCurrentTimeShow(currentRecordTime,true)
MyAudioRecordManager.getInstance().deleteAudioFile()
} else {
showRecordAfter()
}
isStartRecording = false
}
disposableRecordTime?.run {
if (!isDisposed){
dispose()
}
}
}
true
}
需要完整代碼的可私信我