Recording program based on the handler architecture

Source: Internet
Author: User

My app recently needed a recording function, so I searched this article

The communication between the recording thread and the main thread in the article is achieved by accessing the external class member variable through the inner class.

while (IsRecord = = True) {//isrecord is a member variable of an external class readsize = Audiorecord.read (audiodata, 0, buffersizeinbytes); Audiorecord.error_invalid_operation! = readsize) {try {fos.write (audiodata);} catch (IOException e) {E.printstacktrace ();}}}


One of their own Java syntax is not very familiar, and I think this method of extensibility is not good, so decided to use handler to communicate with the main thread

However, to receive the message from the main thread, the child threads are bound to call the loop method of the Looper class, which is a dead loop and the parameter is empty (unable to insert the callback)

    public void Run () {        super.run ();        Looper.prepare ();        Looper.loop ();//Once you enter this function, it will not come out    }

The child thread cannot have both looper.loop () and while (), so I think of a workaround

The statement in the while is processed in an event, and then called Handler sends the event again to itself until the stop event of the main thread is received

It turns out that this method is feasible, and there is no time slot waste compared to timer mode.

On the Code

Package com.hp.speechclient;/** * Created by Administrator on 15-7-16. */import Java.lang.thread;import Java.io.fileinputstream;import Java.io.fileoutputstream;import Java.io.ioexception;import Java.io.filenotfoundexception;import Android.util.log;import Android.os.Handler;import Android.os.message;import Android.os.looper;import Android.os.bundle;import Android.os.environment;import Android.content.context;import Android.media.audioformat;import Android.media.audiorecord;import    Android.media.mediarecorder;public class Recordthread extends Thread {private Context muictx;    Private Handler Muihandler;    Private Boolean brecording = false;    FileOutputStream mspeechstream = null;    Private Audiorecord Maudiorecord;    private int munitbufsize;    private static String TAG = RecordThread.class.getSimpleName ();        Public Recordthread (Context ctx, Handler Handler) {muictx = CTX;        Muihandler = handler; Munitbufsize = Audiorecord.getminbuffersize (16000, Audioformat.        Channel_in_mono, Audioformat.encoding_pcm_16bit); Maudiorecord = new Audiorecord (MediaRecorder.AudioSource.MIC, 16000, Audioformat.channel_in_mono,    Audioformat.encoding_pcm_16bit, munitbufsize);            } private Handler Mhandler = new Handler () {@Override public void Handlemessage (Message msg) {            Super.handlemessage (msg);                    Switch (msg.what) {case Commonmsg.rec_stop: {brecording = false;                Break                    } case Commonmsg.rec_start: {brecording = true;                    Startrecord ();                Break } case Commonmsg.unit_rec_fin: {if (brecording) {Message reply                        = Mhandler.obtainmessage (Commonmsg.unit_rec_start);                    Mhandler.sendmessage (reply);                        }else{Stoprecord (); Message reply = MuihaNdler.obtainmessage (Commonmsg.rec_fin);                    Muihandler.sendmessage (reply);                } break;                    } case Commonmsg.unit_rec_start: {recordunit ();                Break                    } default:{assert false;                Break    }            }        }    };        public void Run () {super.run ();        Looper.prepare ();    Looper.loop ();        } private void Startrecord () {maudiorecord.startrecording (); try {mspeechstream = new FileOutputStream (Commonmsg.speech_path + ". Raw");//Create an accessible byte file} catch (Exce        Ption e) {assert false;    }//Start a small recording recordunit ();        } private void Stoprecord () {maudiorecord.stop ();        try {mspeechstream.close ();//Close write stream mspeechstream = null;   } catch (IOException e) {assert false;     } converttowav (commonmsg.speech_path+ ". Raw", commonmsg.speech_path+ ". wav");         } private void Recordunit () {//new A byte array is used to store some byte data, size is buffer size byte[] Audiodata = new Byte[munitbufsize];        int readsize = 0;        ReadSize = Maudiorecord.read (audiodata, 0, munitbufsize);            if (audiorecord.error_invalid_operation! = readsize) {try {mspeechstream.write (audiodata);            } catch (IOException e) {assert false;        }} Message Reply = Mhandler.obtainmessage (Commonmsg.unit_rec_fin);    Mhandler.sendmessage (reply);            } protected void Finalize () {try {super.finalize ();        Maudiorecord.release ();//release resource maudiorecord = null;        }catch (Throwable e) {assert false;    }} public Handler GetHandler () {return mhandler; } private void Converttowav (String infilename, String outfilename) {FileInputStream In = null;        FileOutputStream out = null;        Long Totalaudiolen = 0;        Long Totaldatalen = Totalaudiolen + 36;        int samplerate = 16000;        int channels = 1;        byte bitDepth = 16;        Long byterate = bitDepth * samplerate * CHANNELS/8;        byte[] data = new Byte[munitbufsize];            try {in = new FileInputStream (infilename);            out = new FileOutputStream (outfilename);            Totalaudiolen = In.getchannel (). Size ();            Totaldatalen = Totalaudiolen + 36;            Writewavefileheader (out, Totalaudiolen, Totaldatalen, samplerate, channels, bitDepth);            while (In.read (data)! =-1) {out.write (data);            } in.close ();        Out.close ();        } catch (FileNotFoundException e) {assert false;        } catch (IOException e) {assert false;         }} private void Writewavefileheader (FileOutputStream out, long Totalaudiolen,                            Long Totaldatalen, int samplerate, int channels, byte bitDepth) throws IOException        {int byterate = bitDepth * samplerate * CHANNELS/8;        Byte[] Header = new byte[44]; Header[0] = ' R ';        Riff/wave header header[1] = ' I ';        HEADER[2] = ' F ';        HEADER[3] = ' F ';        HEADER[4] = (byte) (Totaldatalen & 0xff);        HEADER[5] = (byte) ((Totaldatalen >> 8) & 0xff);        HEADER[6] = (byte) ((Totaldatalen >>) & 0xff);        HEADER[7] = (byte) ((Totaldatalen >>) & 0xff);        Header[8] = ' W ';        HEADER[9] = ' A ';        HEADER[10] = ' V ';        HEADER[11] = ' E '; HEADER[12] = ' f ';        ' FMT ' chunk header[13] = ' m ';        HEADER[14] = ' t ';        HEADER[15] = "; HEADER[16] = 16;        4 bytes:size of ' FMT ' chunk header[17] = 0;        HEADER[18] = 0;        HEADER[19] = 0; HEADER[20] = 1;        Format = 1 Header[21] = 0; HeaDER[22] = (byte) channels;        HEADER[23] = 0;        HEADER[24] = (byte) (Samplerate & 0xff);        HEADER[25] = (byte) ((Samplerate >> 8) & 0xff);        HEADER[26] = (byte) ((Samplerate >>) & 0xff);        HEADER[27] = (byte) ((Samplerate >>) & 0xff);        HEADER[28] = (byte) (Byterate & 0xff);        HEADER[29] = (byte) ((Byterate >> 8) & 0xff);        HEADER[30] = (byte) ((Byterate >>) & 0xff);        HEADER[31] = (byte) ((Byterate >>) & 0xff); HEADER[32] = (byte) (channels * BITDEPTH/8);        Block align header[33] = 0; HEADER[34] = 16;        Bits per sample header[35] = 0;        HEADER[36] = ' d ';        HEADER[37] = ' a ';        HEADER[38] = ' t ';        HEADER[39] = ' a ';        HEADER[40] = (byte) (Totalaudiolen & 0xff);        HEADER[41] = (byte) ((Totalaudiolen >> 8) & 0xff);        HEADER[42] = (byte) ((Totalaudiolen >>) & 0xff); HeaDER[43] = (byte) ((Totalaudiolen >>) & 0xff);    Out.write (header, 0, 44); }}


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Recording program based on the handler architecture

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.