Design _android of Android imitation micro-letter voice Chat interface

Source: Internet
Author: User
Tags prepare uuid

A period of time did not watch the video, last night smoked a little time, and saw the next big God video tutorial, and took time to write a study record. The code is basically the same as the teacher said, and there are many similar blogs on the internet. I just wrote it in the Androidstudio environment.

--The main interface code--

 public class Mainactivity extends activity {private ListView Mlistview;
 Private arrayadapter<recorder> Madapter;
 Private list<recorder> Mdatas = new arraylist<recorder> ();
 Private Audiorecorderbutton Maudiorecorderbutton;

 Private View Animview;
  @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
  Setcontentview (R.layout.activity_main);
  Mlistview = (ListView) Findviewbyid (R.id.id_listview);
  Maudiorecorderbutton = (Audiorecorderbutton) Findviewbyid (R.id.id_recorder_button); Maudiorecorderbutton.setfinishrecordercallback (New Audiorecorderbutton.audiofinishrecordercallback () {public void
    OnFinish (float seconds, String FilePath) {Recorder recorder = new recorder (seconds, filePath);
    Mdatas.add (recorder);
    Update Data madapter.notifydatasetchanged ();
   Set Position mlistview.setselection (Mdatas.size ()-1);

  }
  });
  Madapter = new Recoderadapter (this, mdatas); Mlistview.setadapter (Madapter); ListView Item Click event Mlistview.setonitemclicklistener (New Onitemclicklistener () {public void Onitemclick (Adapterview <?> arg0, view view, int position, long ID {//Sound playback animation if (Animview!= null) {Animview.setbackgroundr
     Esource (R.DRAWABLE.ADJ);
    Animview = null;
    } Animview = View.findviewbyid (R.id.id_recoder_anim);
    Animview.setbackgroundresource (R.drawable.play_anim);
    animationdrawable animation = (animationdrawable) animview.getbackground ();
    Animation.start (); Play the recording Mediaplayermanager.playsound (Mdatas.get (position). FilePath, New Mediaplayer.oncompletionlistener () {Pub
     LIC void Oncompletion (MediaPlayer MP) {///after playback is complete modify the picture Animview.setbackgroundresource (R.DRAWABLE.ADJ);
   }
    });
 }
  });
  } @Override protected void OnPause () {super.onpause ();
 Mediaplayermanager.pause ();
  } @Override protected void Onresume () {super.onresume ();
 Mediaplayermanager.resume (); } @Override Protectedvoid OnDestroy () {Super.ondestroy ();
 Mediaplayermanager.release ();

 }

-Customize button ——-

/** * @param * @author LDM * @description Custom button * @time 2016/6/25 9:26/public class Audiorecorderbutton Exten
 DS button {//button normal state (default) private static final int state_normal = 1;
 Recording status private static final int state_recording = 2;
 Recording cancellation State private static final int state_cancel = 3;
 Record current state private int mcurrentstate = State_normal;
 Whether to start recording flag Private Boolean isrecording = false;
 Determine whether to remove the private static final int distance_y_cancel = 50 by sliding the distance on the button;
 dialog box management tool class private Dialogmanager mdialogmanager;
 Recording management tool class private Audiomanager maudiomanager;
 Record recording time private float mtime;
 Whether to trigger Longclick private Boolean mready;
 Recording preparation private static final int msg_audio_prepared = 0x110;
 Volume changes private static final int msg_voice_changed = 0x111;

 Cancel the prompt dialog box private static final int msg_dialog_dimiss = 0x112; /** * @description Get volume size thread * @author LDM * @time 2016/6/25 9:30 * @param * * Private Runnable MGETVOICELEVELRU

nnable = new Runnable () {  public void Run () {while (isrecording) {//judge is recording try {thread.sleep (100); Mtime + + 0.1f;//recording time calculation mhandler.sendemptymessage (msg_voice_changed);//Send message every 0.1 seconds catch (Interruptedexception e)
    {E.printstacktrace ();

 }
   }
  }
 };
    Private Handler Mhandler = new Handler () {@Override public void Handlemessage (msg) {switch (msg.what) {
     Case msg_audio_prepared://Display dialog box Mdialogmanager.showrecordingdialog ();
     IsRecording = true;
     Open a thread to calculate the recording time new Thread (mgetvoicelevelrunnable). Start ();
    Break
     Case msg_voice_changed://Update Sound Mdialogmanager.updatevoicelevel (Maudiomanager.getvoicelevel (7));
    Break
     Case Msg_dialog_dimiss://Cancel dialog box Mdialogmanager.dimissdialog ();
   Break
  Super.handlemessage (msg);


 }
 };
  Public Audiorecorderbutton (context, AttributeSet attrs) {Super (context, attrs);
  Mdialogmanager = new Dialogmanager (context); The recording file holds the address String dir = Environment.getexternalstoragedirectory () + "/ldm_voice";
  Maudiomanager = Audiomanager.getinstance (dir); Maudiomanager.setonaudiostatelistener (New Audiomanager.audiostatelistener () {public void wellprepared () {MHandler
   . Sendemptymessage (msg_audio_prepared);

  }
  }); Because this class is a button, you add a listener event Setonlongclicklistener (new Onlongclicklistener () {public boolean onlongclick (View v) in the construction method
    {Mready = true;
    Maudiomanager.prepareaudio ();
   return false;
 }
  });
 The public Audiorecorderbutton {This (context, NULL); /** * @description Callback after completion of recording * @author LDM * @time 2016/6/25 11:18 * @param * * Public interface Audiofinishre
 cordercallback {void onfinish (float seconds, String FilePath);

 Private Audiofinishrecordercallback Finishrecordercallback;
 public void Setfinishrecordercallback (Audiofinishrecordercallback listener) {finishrecordercallback = listener; /** * @param * @description ontouchevent event for button processing * @author LDM * @time 2016/6/25 9:35 * * @Override public boolean ontouchevent (Motionevent event) {//Get touchevent status
  int action = Event.getaction ();
  Gets the x-axis coordinate int x = (int) event.getx ();

  Gets the y-coordinate int y = (int) event.gety ();
    Switch (action) {case motionevent.action_down://finger press changestate (state_recording);
   Break Case motionevent.action_move://Finger Move if (isrecording) {//To determine whether or not to cancel if (wanttocancle (x, Y) in accordance with x,y coordinates) {CH
     Angestate (State_cancel);
     else {changestate (state_recording);
   }} break;
     Case motionevent.action_up://Finger Release if (!mready) {reset ();
    Return Super.ontouchevent (event);
     } if (!isrecording | | Mtime < 0.6f) {//If time is less than 0.6s, prompt recording of short mdialogmanager.tooshort ();
     Maudiomanager.cancel ();
    Delay Display dialog box mhandler.sendemptymessagedelayed (Msg_dialog_dimiss, 1000);
else if (mcurrentstate = = state_recording) {//If the status is recording, end the recording Mdialogmanager.dimissdialog ();     Maudiomanager.release ();
     if (finishrecordercallback!= null) {Finishrecordercallback.onfinish (Mtime, Maudiomanager.getcurrentfilepath ());
     } else if (mcurrentstate = state_cancel) {//Want to cancel Mdialogmanager.dimissdialog ();
    Maudiomanager.cancel ();
    Reset ();

  Break
 Return Super.ontouchevent (event);
  /** * Recovery status and sign bit/private void reset () {isrecording = false;
  Mtime = 0;
  Mready = false;
 Changestate (State_normal);
  Private Boolean wanttocancle (int x, int y) {//Exceed button width if (x < 0 | | | x > getwidth ()) {return true;
  }//exceeds the height of the button if (Y <-distance_y_cancel | | | y > getheight () + Distance_y_cancel) {return true;
 return false; /** * @param * @description Change button Display according to state * @author LDM * @time 2016/6/25 9:36/private void Changestat
   E (int state) {if (mcurrentstate!= state) {mcurrentstate = state; Switch (state) {case State_normal:setbackgroundresoUrce (R.drawable.btn_recorder_normal);
     SetText (R.string.str_recorder_normal);

    Break
     Case State_recording:setbackgroundresource (r.drawable.btn_recorder_recording);
     SetText (r.string.str_recorder_recording);
     if (isrecording) {mdialogmanager.recording ();

    } break;
     Case State_cancel:setbackgroundresource (r.drawable.btn_recorder_recording);
     Mdialogmanager.wanttocancel ();
     SetText (R.string.str_recorder_want_cancel);
   Break

 }
  }
 }
}

--Dialog management tools class--

/** * @description Dialog Management Tool class * @author LDM * @time 2016/6/25 11:53 * @param/public class Dialogmanager {//Play
 Out dialog box private Dialog mdialog;
 Recording icon Private ImageView Micon;
 Volume display icon private ImageView mvoice;
 dialog box prompts the text private TextView mlable;


 Contextual object private context Mcontext;
 Public Dialogmanager {this.mcontext = context;  /** * @param * @description Display dialog box * @author LDM * @time 2016/6/25 9:56/public void Showrecordingdialog ()
  {///Sytle instantiated Dialog mdialog = new Dialog (Mcontext, R.style.audiodialog) according to the specified
  Layoutinflater inflater = Layoutinflater.from (Mcontext);
  View view = Inflater.inflate (R.layout.dialog_recorder, NULL);
  Mdialog.setcontentview (view);
  Micon = (ImageView) View.findviewbyid (R.id.id_recorder_dialog_icon);
  Mvoice = (ImageView) View.findviewbyid (R.id.id_recorder_dialog_voice);
  Mlable = (TextView) View.findviewbyid (R.id.id_recorder_dialog_label);
 Mdialog.show (); /** * @param * @description isdialog box for recording status * @author LDM * @time 2016/6/25 10:08/public void recording () {if (Mdialog!= null && Mdialo
   G.isshowing ()) {micon.setvisibility (view.visible);
   Mvoice.setvisibility (view.visible);
   Mlable.setvisibility (view.visible);
   Micon.setimageresource (R.drawable.recorder);
  Mlable.settext ("Slip on the finger, Cancel to send"); }/** * @param * @description Cancel Recording Status dialog box * @author LDM * @time 2016/6/25 10:08/public void Wanttocancel (
   {if (Mdialog!= null && mdialog.isshowing ()) {micon.setvisibility (view.visible);
   Mvoice.setvisibility (View.gone);
   Mlable.setvisibility (view.visible);
   Micon.setimageresource (R.drawable.cancel);
  Mlable.settext ("Loosen the finger, Cancel to send");
  }/** * @param * @description time Too Short dialog box * @author LDM * @time 2016/6/25 10:09/public void Tooshort () {
   if (mdialog!= null && mdialog.isshowing ()) {//Display status micon.setvisibility (view.visible);
   Mvoice.setvisibility (View.gone); Mlable.setvisibility (View.VISIBLE);
   Micon.setimageresource (R.drawable.voice_to_short);
  Mlable.settext ("Recording time is too Short");
  }/** * @param * @description * @author LDM * @time 2016/6/25 Cancel (Close) dialog */public void Dimissdialog () {
   if (mdialog!= null && mdialog.isshowing ()) {//Display status Mdialog.dismiss ();
  Mdialog = null; }///Show Update Volume Level dialog box public void Updatevoicelevel (int level) {if (Mdialog!= null && mdialog.isshowing ()) {
   Display status micon.setvisibility (view.visible);
   Mvoice.setvisibility (view.visible);
   Mlable.setvisibility (view.visible); Set the ID of the picture, the sound picture we put in the drawable is in v+ number format int resid = Mcontext.getresources (). Getidentifier ("V" + level, "drawable", Mcont
   Ext.getpackagename ());
  Mvoice.setimageresource (RESID);

 }
 }

}

--Sound Playback tool class--

/** * @param * @author LDM * @description Play Sound Tool class * @time 2016/6/25 11:29/public class Mediaplayermanager {//Play
 Audio API class: MediaPlayer private static MediaPlayer Mmediaplayer;

 Whether the private static Boolean ispause is paused;  /** * @param * FilePath: File path * Oncompletionlistener: Playback complete listening * @description play sound * @author LDM * @time 2016/6/25 11:30 */public static void PlaySound (String filePath, Mediaplayer.oncompletionlistener oncompletionlistener) {if (
   Mmediaplayer = = null) {Mmediaplayer = new MediaPlayer (); Set an error listener Mmediaplayer.setonerrorlistener (new Mediaplayer.onerrorlistener () {public Boolean onError (Mediapla
     Yer arg0, int arg1, int arg2) {mmediaplayer.reset ();
    return false;
  }
   });
  else {mmediaplayer.reset ();
   try {mmediaplayer.setaudiostreamtype (Android.media.AudioManager.STREAM_MUSIC);
   Mmediaplayer.setoncompletionlistener (Oncompletionlistener);
   Mmediaplayer.setdatasource (FilePath); Mmediaplayer.prepare();
  Mmediaplayer.start (); catch (Exception e) {}}/** * @param * @description paused * @author LDM * @time 2016/6/25 11:31/Pub Lic static void Pause () {if (Mmediaplayer!= null && mmediaplayer.isplaying ()) {//when playing Mmediaplayer.paus
   E ();
  Ispause = true;
  }/** * @param * @description Replay * @author LDM * @time 2016/6/25 11:31/public static void resume () {
   if (Mmediaplayer!= null && ispause) {Mmediaplayer.start ();
  Ispause = false; 
  }/** * @param * @description release operation * @author LDM * @time 2016/6/25 11:32/public static void releases () {
   if (Mmediaplayer!= null) {mmediaplayer.release ();
  Mmediaplayer = null;

 }
 }

-– Recording Operation Tool class-–

/** * @param * @author LDM * @description Recording Management tool class * @time 2016/6/25 9:39/public class Audiomanager {//audioreco
 RD: The main is the implementation of Edge recording Edge broadcast (AUDIORECORD+AUDIOTRACK) and real-time processing of audio.
 Advantages: Can real-time speech processing, can realize a variety of audio packaging private Mediarecorder mmediarecorder;
 Recording files private String Mdir;
 Current recording file directory private String Mcurrentfilepath;
 Single case mode private static Audiomanager minstance;

 Are you ready for private Boolean isprepare?
 Private construction Method Private Audiomanager (String dir) {mdir = dir; //Publish method to get instance public static Audiomanager getinstance (String dir) {if (minstance = null) {synchronized (audiom
    Anager.class) {if (minstance = = null) {minstance = new Audiomanager (dir);
 }} return minstance; /** * @param * @author LDM * @description Recording Preparation Complete Callback interface * @time 2016/6/25 11:14/public interface Audiosta
 Telistener {void wellprepared ();

 Public Audiostatelistener Maudiostatelistener; /** * @param * @description Settings callback method for external class calls * @author LDM * @time 2016/6/25 11: */public void Setonaudiostatelistener (Audiostatelistener listener) {Maudiostatelistener = listener;
  /** * @param * @description Recording Preparation work * @author LDM * @time 2016/6/25 11:15/public void Prepareaudio () {
   try {isprepare = false;
   File dir = new file (Mdir);
   if (!dir.exists ()) {dir.mkdirs ();//file does not exist, create file} String FileName = Generatefilename ();
   File File = new file (dir, fileName);
   Mcurrentfilepath = File.getabsolutepath ();
   Mmediarecorder = new Mediarecorder ();
   Sets the output file path Mmediarecorder.setoutputfile (File.getabsolutepath ());
   Set the Mediarecorder audio source as Microphone mmediarecorder.setaudiosource (MediaRecorder.AudioSource.MIC);
   Set the audio format to Raw_amr Mmediarecorder.setoutputformat (MediaRecorder.OutputFormat.RAW_AMR);
   Set the audio encoding to AMR_NB Mmediarecorder.setaudioencoder (MediaRecorder.AudioEncoder.AMR_NB);
   Prepare the recording mmediarecorder.prepare ();
   To start, you must call Mmediarecorder.start () after prepare ();
   Ready to complete isprepare = true; if (Maudiostatelistener!= null) {maudiostatelistener.wellprepared ();
  } catch (Exception e) {e.printstacktrace (); }/** * @param * @description randomly generated recording file name * @author LDM * @time 2016/6/25,/private String Generatefilen
 Ame () {///randomly generate different UUID return Uuid.randomuuid (). toString () + ". Amr"; /** * @param * @description Get Volume value * @author LDM * @time 2016/6/25 9:49/public int getvoicelevel (int maxl EVEL) {if (Isprepare) {try {//Getmaxamplitude returns the maximum value is 32767 return maxlevel * Mmediarecorder.getmaxamplitu
   De ()/32768 + 1;//Returns the result between 1-7} catch (Exception e) {e.printstacktrace ();
 } return 1; /** * @param * @description Releasing resources * @author LDM * @time 2016/6/25 9:50/public void release () {Mmediare
  Corder.stop ();
  Mmediarecorder.reset ();
 Mmediarecorder = null; /** * @param * @description Recording cancellation * @author LDM * @time 2016/6/25 9:51/public void Cancel ()
  ; if (McurrentfilEpath!= null) {//Cancel the recording after deleting the corresponding file = new file (Mcurrentfilepath);
   File.delete ();
  Mcurrentfilepath = null; }/** * @param * @description Get current file path * @author LDM * @time 2016/6/25 9:51/public String Getcurrentfi
 Lepath () {return mcurrentfilepath;

 }
}

There are comments in the code, do not map, and micro-letter voice chat interface, so called imitation micro-letter, hehe. You can also see the effect when you run it. All code can be downloaded from here: Http://xiazai.jb51.net/201611/yuanma/AndroidWXchat (jb51.net). rar

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.