Android mediarecorder allows you to pause resumable recording.

Source: Internet
Author: User

Android mediarecorder allows you to pause resumable recording.

I recently studied the mediarecorder recording function and found that after the pause, I continue recording. I have little online reference information. Now I will share my learning achievements with you:

The basic principle is as follows: mediarecorder uses mic recording, and the system does not have its own pause function. Each time the recording is paused, the recording ends. Now, my design idea is: when the mediarecorder recording is paused, save the recorded audio A, pause the recording again, and retain the recorded audio B, and so on until the end of the recording, read the previously saved a, B ...... And merge them together. Technologies involved: file storage and reading, audio merging, etc.

Audio merging: Set mediarecorder's audio output format to mmediarecorder01.setoutputformat (mediarecorder. outputformat. raw_amr );
Mmediarecorder01. setaudioencoder (mediarecorder. audioencoder. amr_nb); the output format is Amr. The file header of the audio file of AMR is a fixed 6-byte fixed character,. amr file and B. to merge an AMR file, you only need to read B from the byte stream, remove the first six bytes, merge it with the byte stream of A, and save it. Then, audio merging is realized, it does not involve complicated Audio Encoding issues. (Mediarecorder has many audio output formats, such as jpgg and MP3. The principle of synthesis is similar. You only need to pay attention to the format of their audio file header .)

 

 

Resource code:

Http://download.csdn.net/detail/wanli_smile/4410240

There is a picture with the truth:

 

Public class ex07 extends activity {private imagebutton mybutton1; private imagebutton mybutton2; private imagebutton mybutton3; private imagebutton success; private button mybutton; private listview mylistview1; private string strtempfile = "yyt _"; private file myrecaudiofile;/** recording storage path **/private file myrecaudiodir; private file myplayfile; private mediarecorder mmediarecorder01; private int mminute; privat E Boolean xx = true;/** audio file list **/private arraylist <string> recordfiles; private arrayadapter <string> adapter; private textview mytextview1; /** the file has **/private Boolean sdcardexit;/** whether to stop recording **/private Boolean isstoprecord; /** button background image flag **/private Boolean sigle = false; private string length1 = NULL; private final string suffix = ". amr ";/** pause button **/button buttonpause;/** record the desired AMR audio files **/private arraylist <string> List; int second = 0; int minute = 0;/** timer **/Timer timer;/** whether to suspend flag **/private Boolean ispause; /** pause **/private Boolean inthepause;/** called when the activity is first created. * // @ overridepublic void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); // The pause flag bit is falseispause = false; // The pause status flag bit inthepause = false; // initialize listlist = new arraylist <string> (); // four buttons Mybutton1 = (imagebutton) findviewbyid (R. id. imagebutton01); mybutton2 = (imagebutton) findviewbyid (R. id. imagebutton02); mybutton3 = (imagebutton) findviewbyid (R. id. imagebutton03); mybutton4 = (imagebutton) findviewbyid (R. id. imagebutton04); mybutton = (button) findviewbyid (R. id. mybutton); buttonpause = (button) findviewbyid (R. id. mypuase); mylistview1 = (listview) findviewbyid (R. id. listview01); mytextview1 = (Textview) findviewbyid (R. id. textview01); mybutton2.setenabled (false); mybutton3.setenabled (false); mybutton4.setenabled (false); myplayfile = NULL; // determine whether to insert sdcardexit = environment into the SD card. getexternalstoragestate (). equals (Android. OS. environment. media_mounted); // obtain the SD card path as the recording file location if (sdcardexit) {string pathstr = environment. getexternalstoragedirectory (). getpath () + "/yyt"; myrecaudiodir = new file (pathstr); If (! Myrecaudiodir. exists () {myrecaudiodir. mkdirs (); log. V ("Recording", "Create a recording file! "+ Myrecaudiodir. exists ();} // environment. getexternalstoragedirectory (). getpath () + "/" + prefix + "/";} // get. arm file getrecordfiles (); adapter = new arrayadapter <string> (this, android. r. layout. simple_list_item_1, recordfiles); // Add mylistview1.setadapter (adapter) to the arrayadater listview object; // recording mybutton1.setonclicklistener (New imagebutton. onclicklistener () {@ overridepublic void onclick (view V) {Second = 0; minute = 0; List. clear (); // calendar c = calendar. getinstance (); // intmminute1 = C. get (calendar. minute); sigle = true; // todo auto-generated method stub start (); If (sigle = false) {mybutton1.setbackgroundresource (R. drawable. record_hover1);} else {mybutton1.setbackgroundresource (R. drawable. record_dis1); mybutton2.setbackgroundresource (R. drawable. stop_hover2); mybutton3.setbackgroundresource (R. drawab Le. play_hover1); mybutton4.setbackgroundresource (R. drawable. delete_hover) ;}}}); // stop mybutton2.setonclicklistener (New imagebutton. onclicklistener () {@ overridepublic void onclick (view v) {xx = false; sigle = true; timer. cancel (); // todo auto-generated method stub // write the file to suspend processing! Add the speech in the list to synthesize it. If (ispause) {// press the end key in the paused state to process the list. If (inthepause) {getinputcollection (list, false );} // The else {list. add (myrecaudiofile. getpath (); recodestop (); getinputcollection (list, true);} // restores the flag ispause = false; inthepause = false; buttonpause. settext ("Pause recording"); // adapter. add (myrecaudiofile. getname ();} // If the recording has not been paused, else {If (myrecaudiofile! = NULL) {// stop the recording mmediarecorder01.stop (); mmediarecorder01.release (); mmediarecorder01 = NULL; // send the recorded audio file to adapteradapter. add (myrecaudiofile. getname (); decimalformat df = new decimalformat ("#. 000 "); If (myrecaudiofile. length () <= 1024*1024) {// length1 = (myrecaudiofile. length ()/1024.0) + ""; length1 = DF. format (myrecaudiofile. length ()/1024.0) + "K";} else {// length1 = (myrecaudiofile. length ()/1024.0/102 4) + ""; // decimalformat df = new decimalformat ("#. 000 "); length1 = DF. format (myrecaudiofile. length ()/1024.0/1024) + "M";} system. out. println (length1); mytextview1.settext ("stop" + myrecaudiofile. getname () + "file size:" + length1); mybutton2.setenabled (false) ;}} if (sigle = false) {mybutton2.setbackgroundresource (R. drawable. stop_hover2);} else {mybutton1.setbackgroundresource (R. drawable. record_hover1); mybutt On2.setbackgroundresource (R. drawable. stop1); mybutton3.setbackgroundresource (R. drawable. play_hover1); mybutton4.setbackgroundresource (R. drawable. delete_hover);} // stop recording isstoprecord = true;}); // play mybutton3.setonclicklistener (New imagebutton. onclicklistener () {@ overridepublic void onclick (view v) {sigle = true; // todo auto-generated method stubif (myplayfile! = NULL & myplayfile. exists () {// open the player openfile (myplayfile);} else {toast. maketext (ex07.this, "you selected an empty file", toast. length_long ). show (); log. D ("no file selected", "No file selected");} If (sigle = false) {mybutton3.setbackgroundresource (R. drawable. play_hover1);} else {mybutton1.setbackgroundresource (R. drawable. record_hover1); mybutton2.setbackgroundresource (R. drawable. stop_hover2); mybutton3.setbackgroundresource (R. drawable. Play1); mybutton4.setbackgroundresource (R. drawable. delete_hover) ;}}); // Delete mybutton4.setonclicklistener (New onclicklistener () {@ overridepublic void onclick (view v) {sigle = true; // todo auto-generated method stubif (myplayfile! = NULL) {// Delete the adapter first. remove (myplayfile. getname (); // Delete the object if (myplayfile. exists () myplayfile. delete (); mytextview1.settext ("delete finished! ");} If (sigle = false) {mybutton4.setbackgroundresource (R. drawable. delete_hover);} else {mybutton1.setbackgroundresource (R. drawable. record_hover1); mybutton2.setbackgroundresource (R. drawable. stop_hover2); mybutton3.setbackgroundresource (R. drawable. play_hover1); mybutton4.setbackgroundresource (R. drawable. delete_dis) ;}}});/*** pause button to record the previously saved audio file */buttonpause. setonclicklistener (New onclicklistener () {@ ov Erridepublic void onclick (view v) {// todo auto-generated method stubispause = true; // The recording has been paused. click the button again to start recording, the recording status is in the recording if (inthepause) {buttonpause. settext ("Pause recording"); Start (); inthepause = false;} // recording in progress. Click pause. The recording status is now else pause {// the file name of the currently recording, full List. add (myrecaudiofile. getpath (); inthepause = true; recodestop (); // start (); buttonpause. settext ("Continue recording"); // The timer stops timer. cancel () ;}}); mylistview1.setonitemclicklistener (New adapterview. Onitemclicklistener () {@ overridepublic void onitemclick (adapterview <?> Arg, view arg1, int arg2, long arg3) {// todo auto-generated method stub // The delete button and play button enablemybutton3.setenabled (true) when a single file name is clicked ); mybutton4.setenabled (true); myplayfile = new file (myrecaudiodir. getabsolutepath () + file. separator + (textview) arg1 ). gettext (). tostring (); decimalformat df = new decimalformat ("#. 000 "); If (myplayfile. length () <= 1024*1024) {length1 = DF. format (myplayfile. length ()/1024.0) + "K" ;} Else {length1 = DF. format (myplayfile. length ()/1024.0/1024) + "M";} mytextview1.settext ("You selected" + (textview) arg1 ). gettext (). tostring () + "file size:" + length1); toast. maketext (ex07.this, "you selected" + (textview) arg1 ). gettext () + "file size:" + length1, toast. length_long ). show () ;}}); mybutton. setonclicklistener (New button. onclicklistener () {@ overridepublic void onclick (view v) {// todo auto-generated method stubs Howsize show = new showsize (); string text = show. showsize (); toast. maketext (ex07.this, text, toast. length_long ). show () ;}) ;}protected void recodestop () {If (mmediarecorder01! = NULL &&! Isstoprecord) {// stop the recording mmediarecorder01.stop (); mmediarecorder01.release (); mmediarecorder01 = NULL;} timer. cancel ();}/*** life cycle of the activity. Disable the recording resource during stop */@ overrideprotected void onstop () {// todo auto-generated method stubif (mmediarecorder01! = NULL &&! Isstoprecord) {// stop the recording mmediarecorder01.stop (); mmediarecorder01.release (); mmediarecorder01 = NULL;} super. onstop ();}/*** get all audio files in the directory */private void getrecordfiles () {// todo auto-generated method stubrecordfiles = new arraylist <string> (); If (sdcardexit) {file files [] = myrecaudiodir. listfiles (); If (files! = NULL) {for (INT I = 0; I <files. length; I ++) {If (files [I]. getname (). indexof (". ")> = 0) {// only. amr file string files = files [I]. getname (). substring (files [I]. getname (). indexof (". "); If (files. tolowercase (). equals (". MP3 ") | files. tolowercase (). equals (". amr ") | files. tolowercase (). equals (". MP4 ") recordfiles. add (files [I]. getname () ;}}}// open the recording playback program private void openfile (file F) {intent = new int ENT (); intent. addflags (intent. flag_activity_new_task); intent. setaction (Android. content. intent. action_view); string type = getmimetype (f); intent. setdataandtype (URI. fromfile (F), type); startactivity (intent); // URI uri = Uri. fromfile (f); // mediaplayer = mediaplayer. create (this, Uri); // try {// mediaplayer. prepare (); //} catch (illegalstateexception e) {// todo auto-generated Catch Block // E. printsta Cktrace (); //} catch (ioexception e) {// todo auto-generated Catch Block // E. printstacktrace (); // mediaplayer. start ();} private string getmimetype (file F) {string end = f. getname (). substring (F. getname (). lastindexof (". ") + 1, F. getname (). length ()). tolowercase (); string type = ""; if (end. equals ("MP3") | end. equals ("AAC") | end. equals ("Amr") | end. equals ("MPEG") | end. equals ("MP4") {type = "audio" ;} Else if (end. equals ("jpg") | end. equals ("GIF") | end. equals ("PNG") | end. equals ("Jpeg") {type = "image";} else {type = "*";} type + = "/"; return type;} private void start () {timertask = new timertask () {@ overridepublic void run () {// todo auto-generated method stubsecond ++; If (second> = 60) {second = 0; minute ++;} handler. sendemptymessage (1) ;}}; timer = new timer (); timer. schedule (timertask, 1000, 1000); try {If (! Sdcardexit) {toast. maketext (ex07.this, "insert SD card", toast. length_long ). show (); return;} stringmminute1 = gettime (); toast. maketext (ex07.this, "current time:" + mminute1, toast. length_long ). show (); // create an audio file // myrecaudiofile = file. createtempfile (mminute1 ,". amr ", // myrecaudiodir); myrecaudiofile = new file (myrecaudiodir, mminute1 + suffix); mmediarecorder01 = new mediarecorder (); // set the recording to microphone (m) Ediarecorder. audiosource. MIC); mmediarecorder01.setoutputformat (mediarecorder. outputformat. raw_amr); mmediarecorder01.setaudioencoder (mediarecorder. audioencoder. amr_nb); // Save the recording file here. mmediarecorder01.setoutputfile (myrecaudiofile. getabsolutepath (); mmediarecorder01.prepare (); mmediarecorder01.start (); // mmediarecorder01.getmaxamplitude (); // encrypt (); mmediarecorder01.setoninfolist Ener (New oninfolistener () {@ overridepublic void oninfo (mediarecorder Mr, int what, int extra) {// todo auto-generated method stubint A = mr. getmaxamplitude (); toast. maketext (ex07.this, A, 500 ). show () ;}}); mytextview1.settext ("recording ...... "); mybutton2.setenabled (true); mybutton3.setenabled (false); mybutton4.setenabled (false); isstoprecord = false;} catch (ioexception e) {e. printstacktrace () ;}} private string Gettime () {simpledateformat formatter = new simpledateformat ("mm DD, yyyy hh: mm: SS"); Date curdate = new date (system. currenttimemillis (); // obtain the current time string time = formatter. format (curdate); system. out. println ("Current Time"); return time;} handler = new handler () {@ overridepublic void handlemessage (Message MSG) {// todo auto-generated method stubsuper. handlemessage (MSG); mytextview1.settext ("recording time:" + minute + ": "+ Second) ;}};/*** @ Param isaddlastrecord: whether to add the latest recording outside the list, merge together * @ return save the merged stream with characters */Public void getinputcollection (list, Boolean isaddlastrecord) {stringmminute1 = gettime (); toast. maketext (ex07.this, "current time:" + mminute1, toast. length_long ). show (); // create an audio file. Put the merged file here file file1 = new file (myrecaudiodir, mminute1 + suffix); fileoutputstream = NULL; If (! File1.exists () {try {file1.createnewfile ();} catch (ioexception e) {// todo auto-generated catch blocke. printstacktrace () ;}try {fileoutputstream = new fileoutputstream (file1);} catch (ioexception e) {// todo auto-generated catch blocke. printstacktrace ();} // the name of several Recording files generated when the recording is paused, for (INT I = 0; I <list. size (); I ++) {file = new file (string) list. get (I); log. D ("list length", list. size () + ""); Try {fileinputstream = new fileinputstream (File); byte [] mybyte = new byte [fileinputstream. available ()]; // file length: int length = mybyte. length; // header file if (I = 0) {While (fileinputstream. read (mybyte )! =-1) {fileoutputstream. Write (mybyte, 0, length) ;}// after the file is removed, else {While (fileinputstream. Read (mybyte) can be removed )! =-1) {fileoutputstream. write (mybyte, 6, length-6) ;}} fileoutputstream. flush (); fileinputstream. close (); system. out. println ("synthetic file length:" + file1.length ();} catch (exception e) {// todo auto-generated catch blocke. printstacktrace () ;}/// close the stream try {fileoutputstream. close ();} catch (ioexception e) {// todo auto-generated catch blocke. printstacktrace ();} // Add the current recording section // If (isaddlastrecord) {// The recorded section // try {/F Ileinputstream fileinputstream = new fileinputstream (myrecaudiofile); // byte [] mybyte = new byte [fileinputstream. available ()]; // system. out. println (fileinputstream. available () + ""); // while (fileinputstream. read (mybyte )! =-1) {// outputstream. // fileoutputstream. write (mybyte, 6, (fileinputstream. available ()-6); //} // fileoutputstream. flush (); // fileinputstream. close (); // fileoutputstream. close (); // system. out. println ("synthetic file length:" + file1.length (); //} catch (exception e) {// todo auto-generated Catch Block // E. printstacktrace (); //} // after merging a file, delete the part merging file (isaddlastrecord) stored in the paused recording. // adapter. add (file1.getname ();} private void deletelistrecord (Boolean isaddlastrecord) {for (INT I = 0; I <list. size (); I ++) {file = new file (string) list. get (I); If (file. exists () {file. delete () ;}}// when paused, continue recording the audio file if (isaddlastrecord) {myrecaudiofile. delete ();}}}

 

Technical Exchange Group:

187651345

 

 

 

 

 

 

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.