Android multimedia learning 10: Use the audiorecord class to implement your own audio recording program

Source: Internet
Author: User

Compared with mediarecorder, The audiorecord class is closer to the underlying layer and has fewer encapsulated methods. However, the audio recording program that implements an audiorecord is also very

Simple. The sample code is as follows:

 

It is a pity that there is a problem in this instance testing. During recording, there will be buffer over. Cache leakage to be resolved.

 

 

Package demo. camera; <br/> Import Java. io. bufferedinputstream; <br/> Import Java. io. bufferedoutputstream; <br/> Import Java. io. datainputstream; <br/> Import Java. io. dataoutputstream; <br/> Import Java. io. file; <br/> Import Java. io. fileinputstream; <br/> Import Java. io. fileoutputstream; <br/> Import Java. io. ioexception; <br/> Import android. app. activity; <br/> Import android. content. contentvalues; <br/> Import Android. content. intent; <br/> Import android. hardware. camera. autofocuscallback; <br/> Import android. media. audioformat; <br/> Import android. media. audiomanager; <br/> Import android. media. audiorecord; <br/> Import android. media. audiotrack; <br/> Import android. media. mediaplayer; <br/> Import android. media. mediarecorder; <br/> Import android.net. uri; <br/> Import android. OS. asynctask; <br/> Import android. O S. bundle; <br/> Import android. OS. environment; <br/> Import android. provider. mediastore; <br/> Import android. util. log; <br/> Import android. view. view; <br/> Import android. widget. button; <br/> Import android. widget. textview; <br/>/** <br/> * In this instance, we use the audiorecord class to complete our audio recording program <br/> * audiorecord class, we can use three different read methods to complete recording, <br/> * Each method has its own usage <br/> * 1. to instantiate an audiorecord class, we need to input several parameters. <br/> * 1. audiosource: It can be mediarecorder. audiosource. MIC <br/> * 2. samplerateinhz: Specifies the recording frequency, which can be 8000hz or 11025hz. Different hardware devices have different values. <br/> * 3. channelconfig: Specifies the recording channel, it can be audioformat. channel_configuration_mono and audioformat. channel_configuration_stereo <br/> * 4. audioformat: Specifies the recording encoding format, which can be audioformat. encoding_16bit and 8bit. The simulation of 16 bit is better than that of 8 bit, but it consumes more power and storage space. <br/> * 5. buffersize: Recording buffer size: you can use getminbuffersize to obtain <br/> * so that we can instantiate an audiorecord object. <br/> * 2. Create a file to save the recorded content <br/> * same as the previous article <br/> * 3. Open an output stream, point to the created file <br/> * dataoutputstream dos = new dataoutputstream (New bufferedoutputstream (New fileoutputstream (File) <br/> * 4. Now you can start recording, we need to create a byte array to store the audio data returned from audiorecorder. However, <br/> * Note, the defined array is smaller than the buffersize specified when audiorecord is defined. <br/> * short [] buffer = new short [buffersize/4]; <br/> * startrecording (); <br/> * Next, call the read method of audiorecord to read data in a loop. <br/> * In addition, mediaplayer cannot be used to play audio recorded using audiorecord. To achieve playback, we need to <br/> * use the audiotrack class to implement <br/> * The audiotrack class allows us to play original audio data <br/> * <br/> * 1. to instantiate an audiotrack, you also need to input several parameters <br/> * 1. streamtype: there are several constants in audiomanager, one of which is stream_music; <br/> * 2. samplerateinhz: it is best to use the same value as audiorecord <br/> * 3. channelconfig: same as above <br/> * 4. audioformat: Same as above <br/> * 5. buffersize: obtained by using the static method getminbuffersize of audiotrack <br/> * 6. Mode: Udiotrack. mode_stream and mode_static. For the two differences, see <br/> * 2. Open an input stream, point to the file saved in the recorded content, and start playing, while reading and playing <br/>, two asynctask methods are used for recording and playing audio. <br/> */<br/> public class myaudiorecord2 extends activity {</P> <p> private textview stateview; </P> <p> private button btnstart, btnstop, btnplay, btnfinish; </P> <p> private recordtask recorder; <br/> private playtask player; </P> <p> private file audiofile; </P> <p> priv Ate Boolean isrecording = true, isplaying = false; // flag </P> <p> private int frequence = 8000; // recording frequency, in Hz. note that the value here is not well written. errors may occur when the audiorecord object is instantiated. It won't work if I start writing 11025. This depends on the hardware device <br/> private int channelconfig = audioformat. channel_configuration_mono; <br/> private int audioencoding = audioformat. encoding_pcm_16bit; </P> <p> Public void oncreate (bundle savedinstancestate) {<br/> super. oncreate (savedinstancestate); <br/> setcontentview (R. layout. my_audio_record); </P> <p> stateview = (textview) This. findviewbyid (R. id. view_state); <br/> stateview. settext ("prepare to start"); <br/> btnstart = (button) This. findviewbyid (R. id. btn_start); <br/> btnstop = (button) This. findviewbyid (R. id. btn_stop); <br/> btnplay = (button) This. findviewbyid (R. id. btn_play); <br/> btnfinish = (button) This. findviewbyid (R. id. btn_finish); <br/> btnfinish. settext ("Stop playing"); <br/> btnstop. setenabled (false); <br/> btnplay. setenabled (false); <br/> btnfinish. setenabled (false); </P> <p> // here we create a file to save the recording content. <br/> file fpath = new file (environment. getexternalstoragedirectory (). getabsolutepath () + "/data/files/"); <br/> fpath. mkdirs (); // create a folder <br/> try {<br/> // create a temporary file. Note that the format here is. PCM <br/> audiofile = file. createtempfile ("Recording ",". PCM ", fpath); <br/>} catch (ioexception e) {<br/> // todo auto-generated Catch Block <br/> E. printstacktrace (); <br/>}</P> <p> Public void onclick (view v) {<br/> int id = v. GETID (); <br/> switch (ID) {<br/> case R. id. btn_start: <br/> // start recording </P> <p> // start the recording task here <br/> recorder = new recordtask (); <br/> recorder.exe cute (); </P> <p> break; <br/> case R. id. btn_stop: <br/> // stop recording <br/> This. isrecording = false; <br/> // Update Status <br/> // when recording is complete, set it in onpostexecute of recordtask <br/> break; <br/> case R. id. btn_play: </P> <p> player = new playtask (); <br/> player.exe cute (); <br/> break; <br/> case R. id. btn_finish: <br/> // complete playback <br/> This. isplaying = false; <br/> break; </P> <p >}< br/>}</P> <p> class recordtask extends asynctask <void, integer, void >{< br/> @ override <br/> protected void doinbackground (void... arg0) {<br/> isrecording = true; <br/> try {<br/> // activate the output stream to the specified file <br/> dataoutputstream dos = new dataoutputstream (New bufferedoutputstream (New fileoutputstream (audiofile ))); <br/> // obtain the appropriate buffer size based on the defined configurations. <br/> int buffersize = audiorecord. getminbuffersize (frequence, channelconfig, audioencoding); <br/> // instantiate audiorecord <br/> audiorecord record = new audiorecord (mediarecorder. audiosource. mic, frequence, channelconfig, audioencoding, buffersize); <br/> // define the buffer <br/> short [] buffer = new short [buffersize]; </P> <p> // start recording <br/> record. startrecording (); </P> <p> int r = 0; // stores the recording progress <br/> // defines the loop, determine whether to continue recording Based on the isrecording value <br/> while (isrecording) {<br/> // read bytes from buffersize, return the number of short reads <br/> // buffer overflow is always displayed here. I don't know why. I tried several values and it's useless. Todo: to be resolved <br/> int bufferreadresult = record. read (buffer, 0, buffer. length); <br/> // cyclically write the audio data in the buffer to outputstream <br/> for (INT I = 0; I <bufferreadresult; I ++) {<br/> dos. writeshort (buffer [I]); <br/>}< br/> publishprogress (New INTEGER (R )); // report the current progress to the UI thread <br/> r ++; // auto-increment progress value <br/>}< br/> // end of recording <br/> record. stop (); <br/> log. V ("the DOS available:", ":" + audiofile. length (); <br/> dos. close (); <br/>}catch (exception e) {<br/> // todo: handle exception <br/>}< br/> return NULL; <br/>}</P> <p> // This method is triggered when publishprogress is called in the preceding method, this method is executed in the UI thread <br/> protected void onprogressupdate (integer... progress) {<br/> stateview. settext (Progress [0]. tostring (); <br/>}</P> <p> protected void onpostexecute (void result) {<br/> btnstop. setenabled (false); <br/> btnstart. setenabled (true); <br/> btnplay. setenabled (true); <br/> btnfinish. setenabled (false); <br/>}</P> <p> protected void onpreexecute () {<br/> // stateview. settext ("Recording"); <br/> btnstart. setenabled (false); <br/> btnplay. setenabled (false); <br/> btnfinish. setenabled (false); <br/> btnstop. setenabled (true); <br/>}</P> <p> class playtask extends asynctask <void, integer, void >{< br/> @ override <br/> protected void doinbackground (void... arg0) {<br/> isplaying = true; <br/> int buffersize = audiotrack. getminbuffersize (frequence, channelconfig, audioencoding); <br/> short [] buffer = new short [buffersize/4]; <br/> try {<br/> // defines the input stream and writes the audio to the audiotrack class, implement playback <br/> datainputstream Dis = new datainputstream (New bufferedinputstream (New fileinputstream (audiofile ))); <br/> // instance audiotrack <br/> audiotrack = new audiotrack (audiomanager. stream_music, frequence, channelconfig, audioencoding, buffersize, audiotrack. mode_stream); <br/> // start playing <br/> track. play (); <br/> // because audiotrack is playing streams, we need to read while playing <br/> while (isplaying & dis. available ()> 0) {<br/> int I = 0; <br/> while (DIS. available ()> 0 & I <buffer. length) {<br/> buffer [I] = dis. readshort (); <br/> I ++; <br/>}< br/> // write data to audiotrack. <br/>. write (buffer, 0, buffer. length); </P> <p >}</P> <p> // end of playback <br/> track. stop (); <br/> dis. close (); <br/>}catch (exception e) {<br/> // todo: handle exception <br/>}< br/> return NULL; <br/>}</P> <p> protected void onpostexecute (void result) {<br/> btnplay. setenabled (true); <br/> btnfinish. setenabled (false); <br/> btnstart. setenabled (true); <br/> btnstop. setenabled (false); <br/>}</P> <p> protected void onpreexecute () {</P> <p> // stateview. settext ("playing"); <br/> btnstart. setenabled (false); <br/> btnstop. setenabled (false); <br/> btnplay. setenabled (false); <br/> btnfinish. setenabled (true); <br/>}</P> <p >}< br/>}

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.