jetpack compose 录音功能实现

//获取录音权限

@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()

    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值