Notepad for Android project (5)-----Add recording

Source: Internet
Author: User

Sometimes, it is necessary to record important things in the form of voice, this is very common in life, today, the function of adding a recording to Notepad, first look at the picture:

In fact, in the first section of the interface design, you can see the function of Notepad options, where the bottom of the option bar is the third one to add audio.

The main steps are as follows:

1. The interface design of the recording activity.

2. Add Intent to the Voice button's listener and jump to the recording activity, which is also used Startactivityforresult (Intent intent,int requestcode).

3. The recording function is realized in recording activity, and the final recording file path is returned.

4. In the Add notes activity, remove the path of the returned recording file and add the corresponding recording icon to the note.

1 Recording Activity interface design:

Recording the layout file Activity_record.xml

<?xml version= "1.0" encoding= "Utf-8"? ><relativelayout xmlns:android= "http://schemas.android.com/apk/res/ Android "Android:layout_width=" Match_parent "android:layout_height=" match_parent "android:background=" @drawable/ BG "> <linearlayout android:layout_width=" match_parent "android:layout_height=" Match_paren          T "android:orientation=" vertical "android:gravity=" center "android:layout_centerinparent=" true " > <linearlayout android:layout_width= "match_parent" android:layout_height= "Wra P_content "android:orientation=" horizontal "android:gravity=" center "android:layout_margin=" 5DP        "> <imageview android:id=" @+id/iv_record_wave_left "android:layout_width=" Wrap_content " android:layout_height= "wrap_content" android:layout_gravity= "Center" android:layout_margin= "5d P "android:background=" @anIm/record_wave_left "/> <imageview android:id=" @+id/iv_microphone "android:layout_width = "Wrap_content" android:layout_height= "wrap_content" android:layout_gravity= "center" android:src= "@dr Awable/record_microphone_icon "android:layout_margin=" 5DP "/> <imageview android:id=" @ +id/iv_record_wave_right "android:layout_width=" wrap_content "android:layout_height=" Wrap_content "an droid:layout_gravity= "center" android:layout_margin= "5DP" android:background= "@anim/record_wave_righ T "/> </LinearLayout> <textview android:id=" @+id/tv_recordtime "an Droid:layout_width= "Match_parent" android:layout_height= "wrap_content" android:textcolor= "#499df7" an        Droid:textsize= "20SP" android:text= "00:00:00" android:gravity= "center" android:layout_margin= "5DP" /> </linearlayout> <linearlayout android:layout_width= "Match_parent" Android:layo        ut_height= "45DP" android:background= "@drawable/navigationbar_bg" android:layout_alignparentbottom= "true" android:gravity= "center" > <button android:id= "@+id/btn_record" Android: Layout_width= "Wrap_content" android:layout_height= "wrap_content" android:background= "@drawable/tab Bar_record_start "/> </LinearLayout> </RelativeLayout>

Again, the title bar is Title_add.xml, which has been given in the previous sections, where the title is replaced with a "recording" in the Java code.

2 Add intent to the Voice button listener and jump to the recording activity with the code:

Voice case 2:intent = new Intent (Addactivity.this,activityrecord.class); Startactivityforresult (Intent, 4);

3 recording function in recording activity

Now that you want to implement the recording, there are no permissions, so add the Androidmanifest.xml

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

The

            here not only realizes the function of recording, but also realizes the function of timing, audition, and frame-wise animation. There is a comment in the specific code

Package Com.example.notes;import Java.io.file;import Java.io.ioexception;import java.text.simpledateformat;import Java.util.date;import Java.util.timer;import Java.util.timertask;import Android.app.activity;import Android.content.intent;import Android.graphics.drawable.animationdrawable;import Android.media.MediaPlayer; Import Android.media.mediaplayer.oncompletionlistener;import Android.media.mediarecorder;import Android.os.Bundle ; Import Android.os.handler;import Android.os.message;import Android.view.view;import Android.view.view.onclicklistener;import Android.view.window;import Android.widget.button;import Android.widget.imageview;import Android.widget.textview;import Android.widget.toast;public class ActivityRecord Extends Activity {private Button btn_record;private ImageView iv_microphone;private TextView tv_recordtime;private ImageView iv_record_wave_left,iv_record_wave_right;private animationdrawable ad_left,ad_right;private int isrecording = 0;private int isplaying = 0;private TImer mtimer;//Voice Operation object Private MediaPlayer MPlayer = null;private Mediarecorder Mrecorder = null;//Voice save path private String File Path = null; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Requestwindowfeature (Window.feature_custom_title); Setcontentview (R.layout.activity_record); GetWindow (). Setfeatureint (Window.feature_custom_title, R.layout.title_add); TextView title = (TextView) Findviewbyid (r.id.tv_title); Title.settext ("recording"); Button Btn_save = (button) Findviewbyid (R.id.bt_save); Btn_save.setonclicklistener (new Clickevent ()); Button Btn_back = (button) Findviewbyid (r.id.bt_back); Btn_back.setonclicklistener (new Clickevent ()); Btn_record = ( Button) Findviewbyid (R.id.btn_record); Btn_record.setonclicklistener (new Clickevent ()); Iv_microphone = (ImageView) Findviewbyid (R.id.iv_microphone); Iv_microphone.setonclicklistener (new Clickevent ()); Iv_record_wave_left = ( ImageView) Findviewbyid (r.id.iv_record_wave_left); iv_record_wave_right = (ImageView) Findviewbyid (R.Id.iv_record_wave_right); ad_left = (animationdrawable) iv_record_wave_left.getbackground ();//ad_left = ( animationdrawable) iv_record_wave_left.getdrawable (); ad_right = (animationdrawable) iv_record_wave_ Right.getbackground ();//ad_right = (animationdrawable) iv_record_wave_right.getdrawable (); tv_recordTime = (TextView ) Findviewbyid (r.id.tv_recordtime);} Final Handler Handler = new Handler () {public void Handlemessage (Message msg) {switch (msg.what) {Case 1:string time [] = Tv_recordtime.gettext (). toString (). Split (":"); int hour = Integer.parseint (time[0]); int minute = Integer.parseint ( TIME[1]); int second = Integer.parseint (time[2]); if (second <) {second++;} else if (second = = && minute <) {Minute++;second = 0;} if (second = = && minute = = && Hour < 98) {Hour++;minute = 0;second = 0;} Time[0] = hour + ""; time[1] = minute + ""; time[2] = second + "";//Adjust the format to display on the screen if (second <) time[2] = "0" + second;if (mi Nute <) time[1] = "0" + minute;if (Hour < Time[0] = "0" + hour;//shown in TextView tv_recordtime.settext (time[0]+ ":" +time[1]+ ":" +time[2]); break;}}; Class Clickevent implements onclicklistener{@Overridepublic void OnClick (View v) {switch (V.getid ()) {//Click on the Start Recording button case R . Id.btn_record://Start recording if (isrecording = = 0) {//per call recording, can be recorded multiple times, at most satisfactory to, and finally only the last recording file saved, and other delete if (FilePath! = null) {File OldFile = new File (FilePath); Oldfile.delete ();}          Obtain the current time of the system and take that time as the filename simpledateformat formatter = new SimpleDateFormat ("Yyyymmddhhmmss");                   Date curdate = new Date (System.currenttimemillis ());//Gets the current time String str = Formatter.format (curdate);        str = str + "RECORD.AMR";        File dir = new file ("/sdcard/notes/");        File File = new file ("/sdcard/notes/", str);         if (!dir.exists ()) {Dir.mkdir ();        } else{if (File.exists ()) {file.delete (); }}filepath = Dir.getpath () + "/" + str;//Timer Mtimer = new timer ();//Set Mike icon to be non-clickable, iv_microphone.setclickablE (FALSE);//Set the displayed time to 00:00:00tv_recordtime.settext ("00:00:00");//Change the button to stop recording isrecording = 1;btn_ Record.setbackgroundresource (r.drawable.tabbar_record_stop); mrecorder = new Mediarecorder (); Mrecorder.setaudiosource (MediaRecorder.AudioSource.MIC); Mrecorder.setoutputformat ( MediaRecorder.OutputFormat.THREE_GPP); Mrecorder.setoutputfile (FilePath); Mrecorder.setaudioencoder ( MediaRecorder.AudioEncoder.AMR_NB); try {mrecorder.prepare ();} catch (IllegalStateException e) {//TODO auto-generated Catch Blocke.printstacktrace ();} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();} Mrecorder.start (); Mtimer.schedule (new TimerTask () {@Overridepublic void run () {Message message = new Message (); Message.what = 1;handler.sendmessage (message);}},1000, 1000);//Play Animation Ad_left.start (); Ad_right.start ();} Stop recording else{//switch the button to start recording isrecording = 0;btn_record.setbackgroundresource (R.drawable.tabbar_record_start); Mrecorder.stop (); Mtimer.cancel (); mtimer = Null;mrecorder.release (); mrecorder = null;//the Mac iconSet to clickable, iv_microphone.setclickable (TRUE);//Stop animation ad_left.stop (); Ad_right.stop (); Toast.maketext (Activityrecord.this, "Click on the mic icon to audition, click again to end the audition", Toast.length_long). Show (); break;//If you click on the Mike icon, you can go to audition mode, click again, stop playing case r.id.iv_microphone:if (FilePath = = null) Toast.maketext ( Activityrecord.this, "No recording broadcast can play, please record First", Toast.length_long). Show (); else{//Audition if (isplaying = = 0) {isplaying = 1;mplayer = New MediaPlayer (); Tv_recordtime.settext ("00:00:00"); Mtimer = new Timer (); Mplayer.setoncompletionlistener (new Mediacompletion ()); try {mplayer.setdatasource (FilePath); Mplayer.prepare (); Mplayer.start ();} catch (  IllegalArgumentException e) {//Todo auto-generated catch Blocke.printstacktrace ();} catch (SecurityException e) {//TODO Auto-generated catch Blocke.printstacktrace ();} catch (IllegalStateException e) {//Todo auto-generated catch Blocke.printstacktrace ();} catch (IOException e) {//Todo Au To-generated catch Blocke.printstacktrace ();} Mtimer.schedule (New TimerTask () {@Overridepublic void run () {Message message= new Message (); message.what = 1;handler.sendmessage (Message);}}, 1000,1000);//Play Animation Ad_left.start (); Ad_right.start () ;} End Audition else{isplaying = 0;mplayer.stop (); Mplayer.release (); mPlayer = Null;mtimer.cancel (); mtimer = null;//Stop animation ad_ Left.stop (); Ad_right.stop ();}} break;//Click OK button case R.id.bt_save://The path of the final recording file is returned intent intent = getintent (); Bundle B = new bundle (); B.putstring ("Audio", FilePath); Intent.putextras (b); Setresult (RESULT_OK, intent); ActivityRecord.this.finish (); Break;case r.id.bt_back://delete the recorded file before returning the IF (FilePath! = null) {File OldFile = new file ( FilePath); Oldfile.delete ();} ActivityRecord.this.finish (); break;}}} Class Mediacompletion implements oncompletionlistener{@Overridepublic void Oncompletion (MediaPlayer MP) { Mtimer.cancel (); mtimer = null;isplaying = 0;//Stop animation ad_left.stop (); Ad_right.stop (); Toast.maketext (Activityrecord.this, "play Complete", Toast.length_long). Show (); Tv_recordtime.settext ("00:00:00");}}


One of the Animationdrawable class for frame-by-box animation, just need to create a new animated list file in Res/anim, where the animation is in the process of recording and audition, Mike appears on both sides of the waveform, to add beauty to the program.

Animation list file----Mike Left waveform: Record_wave_left.xml

<?xml version= "1.0" encoding= "Utf-8"? ><animation-list xmlns:android= "http://schemas.android.com/apk/res/ Android ">    <item         android:drawable=" @drawable/record_wave_left_01 "        android:duration="/>      <item         android:drawable= "@drawable/record_wave_left_02"        android:duration= "/>        < Item         android:drawable= "@drawable/record_wave_left_03"        android:duration= "/>          <item         " android:drawable= "@drawable/record_wave_left_04"        android:duration= "/>    </animation-list>

Animation list file----Mike Right waveform: Record_wave_right.xml

<?xml version= "1.0" encoding= "Utf-8"? ><animation-list xmlns:android= "http://schemas.android.com/apk/res/ Android ">     <item         android:drawable=" @drawable/record_wave_right_01 "        android:duration=" 500 "/ >      <item         android:drawable= "@drawable/record_wave_right_02"        android:duration= "/>        " <item         android:drawable= "@drawable/record_wave_right_03"        android:duration= "/>          <item"         android:drawable= "@drawable/record_wave_right_04"        android:duration= "/></animation-list >

Here the picture resource file, here is not given, can according to their own needs, change the other, of course, the speed of the animation can be set in the above file duration value.

When applying, you only need to set the corresponding ImageView Backgroud property to "@anim/corresponding filename", you can take advantage of animationdrawable start, stop the animation method, that is, stop (), Start () method.

It is also important to note that in the recording activity in real-time display timing, here is used handler, because the timer thread can not draw the UI, so can not be directly in the TimerTask run method to achieve dynamic display time.

Of course, there are some small features, for example, can be recorded in the interface of multiple recordings, and click on the microphone icon to achieve playback, click again to stop playback, only when the completion of the button to save the last recording file, before the recording file deletion and other such functions, can be seen in the code.

4. In the Add notes activity, remove the path of the returned recording file and add the corresponding recording icon to the note.

Add the following code to Onactivityresult ():

The returned audio file is the else if (Requestcode = = 4) {extras = Data.getextras (); String audiopath = extras.getstring ("audio"); bitmap = Bitmapfactory.decoderesource (Getresources (), R.drawable.record _microphone_icon);//Insert Recording icon Insertbitmap (bitmap,80);}

Here Insertbitmap (bitmap,80), is to be the picture, such as scale, and add it into the EditText code as a function, when used, only need to add the picture bitmap, as well as the scale of the maximum value of the function as the parameter call the function.

This gives the function, which is actually some of the code in the previous section of adding photos.

Scale the picture equal to the appropriate size and add in EditText void Insertbitmap (Bitmap bitmap,int S) {int imgwidth = bitmap.getwidth (); int imgheight = Bitmap.getheight ();d ouble partion = imgwidth*1.0/imgheight;double sqrtlength = math.sqrt (partion*partion + 1);// New thumbnail size Double NEWIMGW = s* (partion/sqrtlength);d ouble newimgh = s* (1/sqrtlength); float Scalew = (float) (Newimgw/imgwi DTH); float Scaleh = (float) (newimgh/imgheight); Matrix MX = new Matrix ();//Scale the original image Mx.postscale (Scalew, Scaleh); bitmap = Bitmap.createbitmap (bitmap, 0, 0, ImgWidth, IMGH Eight, MX, true); final Imagespan Imagespan = new Imagespan (THIS,BITMAP); spannablestring spannablestring = new spannablestring ("test"); Spannablestring.setspan (Imagespan, 0, Spannablestring.length (), spannablestring.span_mark_mark);//cursor moves to the next line//et_notes.append ("\ n"); Editable Editable = Et_notes.geteditabletext (); int selectionindex = Et_notes.getselectionstart (); Spannablestring.getspans (0, Spannablestring.length (), imagespan.class);//Add a picture into EditText Editable.insert ( Selectionindex,spannablestring);//Add a picture and automatically empty two lines of et_notes.append ("\ n");} 

At this point, Notepad to add the recording function has been implemented, because the database has not been used, so there is no record of the deletion and modification of the functions, this later implementation, the implementation of a main line, first set up a good framework, and then realize the function.






Notepad for Android project (5)-----Add recording

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.