android 录音功能核心代码

1.在onCreate方法中追加动态权限获取

if (Build.VERSION.SDK_INT >= 23) {
    int REQUEST_CODE_CONTACT = 101;
    String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.RECORD_AUDIO};
    for (String str : permissions) {
        if (this.checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) {
            this.requestPermissions(permissions, REQUEST_CODE_CONTACT);
            return;
        }
    }
}

2.核心代码

try{
soundFile = new File("/mnt/sdcard/2019.amr");
    if(!soundFile.exists()){
        soundFile.createNewFile();
    }
    mRecorder = new MediaRecorder();
    mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
    mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
    mRecorder.setOutputFile(soundFile.getAbsolutePath());
    mRecorder.prepare();
} catch (IOException e) {
    e.printStackTrace();
}
mRecorder.start();

 

3.在AndroidManifest.xml中追加权限

<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
相关推荐
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页