Android basics tutorial-9.4 use MediaRecord recording
Android basics tutorial-9.4 use MediaRecord recording
Tags (separated by spaces): basic Android tutorial
This section introduces
This section is the last section of the Android multimedia basic API call, bringing about the simple use of MediaRecord,
The usage is very simple. Let's write an example to familiarize yourself with it ~
1. Use MediaRecord to record audio
Running result:
Implementation Code:
Layout code:Activity_main.xml:
MainActivity. java:
Public class MainActivity extends AppCompatActivity {private Button btn_control; private boolean isStart = false; private MediaRecorder mr = null; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); btn_control = (Button) findViewById (R. id. btn_control); btn_control.setOnClickListener (new View. onClickListener (){ @ Override public void onClick (View v) {if (! IsStart) {startRecord (); btn_control.setText (stop recording); isStart = true;} else {stopRecord (); btn_control.setText (Start recording); isStart = false ;}}});} // start recording private void startRecord () {if (mr = null) {File dir = new File (Environment. getExternalStorageDirectory (), sounds); if (! Dir. exists () {dir. mkdirs ();} File soundFile = new File (dir, System. currentTimeMillis () +. amr); if (! SoundFile. exists () {try {soundFile. createNewFile ();} catch (IOException e) {e. printStackTrace () ;}} mr = new MediaRecorder (); mr. setAudioSource (MediaRecorder. audioSource. MIC); // audio input source mr. setOutputFormat (MediaRecorder. outputFormat. AMR_WB); // set the output format to mr. setAudioEncoder (MediaRecorder. audioEncoder. AMR_WB); // sets the encoding format. setOutputFile (soundFile. getAbsolutePath (); try {mr. prepare (); mr. start (); // start recording} Catch (IOException e) {e. printStackTrace () ;}}// stop recording. Release the private void stopRecord () {if (mr! = Null) {mr. stop (); mr. release (); mr = null ;}}}