//获取录音权限
@SuppressLint("SuspiciousIndentation")
@RequiresApi(Build.VERSION_CODES.O)
fun checkPermission()
{
if(ContextCompat.checkSelfPermission(this,
Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED)
{
startRecord()
}
else
{
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.RECORD_AUDIO),100 )
}
}
//权限运行回调
@RequiresApi(Build.VERSION_CODES.O)
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
when(requestCode )
{
100-> if(grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
startRecord()
}
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
//本地文件路径
private fun getSDCardFile(){
if(Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED){
sdcardfile = getExternalFilesDir(null)
// tv_path.text = sdcardfile.toString()
}else{
// toast("未找到内存卡")
}
}
private var sdcardfile : File? = null
private lateinit var mp3File: File
private var recorder : MediaRecorder? = null
@OptIn(ExperimentalPermissionsApi::class)
@RequiresApi(Build.VERSION_CODES.O)
private fun startRecord(){
recorder = MediaRecorder()
recorder?.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder?.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
recorder?.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
recorder?.setAudioChannels(2);
recorder?.setAudioSamplingRate(8000);
recorder?.setAudioEncodingBitRate(32000);
try{
val filet = File.createTempFile("录音_",".mp3",sdcardfile)
if (filet.exists()) {
filet.delete()
// 文件存在
} else {
// 文件不存在
}
var file = File.createTempFile("录音_",".mp3",sdcardfile)
mp3File = file
//设置录音保存路径
recorder?.setOutputFile(file)
//准备和启动录制音频
recorder?.prepare()
recorder?.start()
}catch (e : IOException){
e.printStackTrace()
}
}
//停止录音
@RequiresApi(Build.VERSION_CODES.O)
private fun stopRecord(){
try{
recorder?.stop()
recorder?.release()
recorder = null
}catch (e:Exception){
e.printStackTrace()
}
}