扣丁学堂——MediaRecorder(录音功能)

一丶源码见本文

二丶演示(略)

三丶课程讲解

扣丁学堂——MediaRecorder(录音功能)_第1张图片

扣丁学堂——MediaRecorder(录音功能)_第2张图片

权限设置

<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
MainActivity

public class MainActivity extends AppCompatActivity implements MediaRecorder.OnErrorListener{
    private MediaRecorder mr;
    private boolean prepared = false;
    private Button btnRecorder,btnStop;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnRecorder = (Button) findViewById(R.id.button_recorder);
        btnStop = (Button) findViewById(R.id.button2_stop);
        mr = new MediaRecorder();
        init();
    }
    private void init() {
        mr.reset();
        mr.setAudioSource(MediaRecorder.AudioSource.MIC);//设置音源
        mr.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);//格式
        mr.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);//编码
        //路径
        String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC)+ File.separator+System.currentTimeMillis()+".mp3";
        mr.setOutputFile(path);
        try {
            mr.prepare();
            prepared = true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        btnStop.setEnabled(false);
    }

    public void recorderClick(View view){
        if(prepared){
            mr.start();
            prepared = false;
            btnStop.setEnabled(true);
            btnRecorder.setEnabled(false);
        }
    }

    public void stopClick(View view){
        mr.stop();
        btnStop.setEnabled(false);
        btnRecorder.setEnabled(true);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mr!=null){
            mr.release();
        }
    }

    @Override
    public void onError(MediaRecorder mr, int what, int extra) {
        mr.reset();
    }
}
xml(略)

你可能感兴趣的:(源码,MediaRecorder,录音,扣丁学堂)