Android Basics Getting Started tutorial--9.4 using Mediarecord Recording
tags (space delimited): Android Basics Getting Started Tutorial
Introduction to this section
This section is the last section of the Android multimedia Basic API call, which is a simple use of Mediarecord,
The usage is very simple, we write an example to familiarize with the familiar ~
1. Recording Audio using Mediarecord
Operation result :
Implementation Code :
Layout code:activity_main.xml:
<relativelayout xmlns: Android = "http://schemas.android.com/apk/res/android" xmlns:tools =" Http://schemas.android.com/tools " android:layout_width = "match_parent" android:layout_height =" match_parent " tools:context =". Mainactivity "; <buttonandroid:id="@+id/btn_control"android:layout_width="Wrap_ Content "android:layout_height=" Wrap_content "android:text=" Start recording " /> </relativelayout>
Mainactivity.java:
Public class mainactivity extends appcompatactivity { PrivateButton Btn_control;Private BooleanIsstart =false;PrivateMediarecorder 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 (NewView.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 =NewFile (Environment.getexternalstoragedirectory (),"Sounds");if(!dir.exists ()) {Dir.mkdirs (); } File soundfile =NewFile (Dir,system.currenttimemillis () +". Amr");if(!soundfile.exists ()) {Try{Soundfile.createnewfile (); }Catch(IOException e) {E.printstacktrace (); }} Mr =NewMediarecorder (); Mr.setaudiosource (MediaRecorder.AudioSource.MIC);//Audio input sourceMr.setoutputformat (MediaRecorder.OutputFormat.AMR_WB);//Set output formatMr.setaudioencoder (MediaRecorder.AudioEncoder.AMR_WB);//Set encoding formatMr.setoutputfile (Soundfile.getabsolutepath ());Try{Mr.prepare (); Mr.start ();//Start recording}Catch(IOException e) {E.printstacktrace (); } } }//Stop recording, resource release Private void Stoprecord(){if(Mr! =NULL) {mr.stop (); Mr.release (); Mr =NULL; } }}
Finally, don't forget to add the following permissions in Androidmanifest.xml:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.RECORD_AUDIO"/>
Okay, that's so easy.
2. Sample code download for this section
Recorddemo.zip
This section summarizes:
OK, this section is very simple, is the use of Mediarecorder, is probably the most streamlined section of the entire tutorial
Now ~ hehe ~
Android Basics Getting Started tutorial--9.4 using Mediarecord Recording