Objective:
In fact, recording in Android can be recorded with Mediarecord, the operation is relatively simple. However, the audio cannot be processed. Consider that the project is done in real-time voice can only select Audiorecord for recording. Then live playback can only be played with Audiotrack.
The following are specific implementations:
Public classAudiotrackmanager { Public Static FinalString TAG = "Audiotrackmanager"; PrivateAudiotrack Audiotrack; PrivateDataInputStream Dis; PrivateThread Recordthread; Private BooleanIsstart =false; Private StaticAudiotrackmanager minstance; Private intbuffersize; PublicAudiotrackmanager () {buffersize= Audiotrack.getminbuffersize (8000, Audioformat.channel_out_mono, audioformat.encoding_pcm_16bit); Audiotrack=NewAudiotrack (Audiomanager.stream_music, 8000, Audioformat.channel_out_mono, Audioformat.encoding_pcm_16bit, BufferSize * 2, Audiotrack.mode_stream); } /*** Get a singleton reference * *@return */ Public StaticAudiotrackmanager getinstance () {if(Minstance = =NULL) { synchronized(Audiotrackmanager.class) { if(Minstance = =NULL) {minstance=NewAudiotrackmanager (); } } } returnminstance; } /*** Destroying threading methods*/ Private voidDestroythread () {Try{Isstart=false; if(NULL! = Recordthread && Thread.State.RUNNABLE = =recordthread.getstate ()) { Try{Thread.Sleep (500); Recordthread.interrupt (); } Catch(Exception e) {recordthread=NULL; }} recordthread=NULL; } Catch(Exception e) {e.printstacktrace (); } finally{Recordthread=NULL; } } /*** Start the playback thread*/ Private voidStartthread () {destroythread (); Isstart=true; if(Recordthread = =NULL) {Recordthread=NewThread (recordrunnable); Recordthread.start (); } } /*** Play Thread*/Runnable recordrunnable=NewRunnable () {@Override Public voidrun () {Try{android.os.Process.setThreadPriority (Android.os.Process.THREAD_PRIORITY_URGENT_AUDIO); byte[] Tempbuffer =New byte[buffersize]; intReadcount = 0; while(dis.available () > 0) {Readcount=Dis.read (Tempbuffer); if(Readcount = = Audiotrack.error_invalid_operation | | readcount = =audiotrack.error_bad_value) { Continue; } if(Readcount! = 0 && Readcount! =-1) {audiotrack.play (); Audiotrack.write (Tempbuffer,0, Readcount); }} stopplay (); } Catch(Exception e) {e.printstacktrace (); } } }; /*** Play File * *@paramPath *@throwsException*/ Private voidSetPath (String Path)throwsException {File file=NewFile (path); Dis=NewDataInputStream (Newfileinputstream (file)); } /*** Start Play * *@paramPath*/ Public voidstartplay (String path) {Try{setpath (path); Startthread (); } Catch(Exception e) {e.printstacktrace (); } } /*** Stop playing*/ Public voidStopplay () {Try{destroythread (); if(Audiotrack! =NULL) { if(audiotrack.getstate () = =audiorecord.state_initialized) {audiotrack.stop (); } if(Audiotrack! =NULL) {audiotrack.release (); } } if(Dis! =NULL) {dis.close (); } } Catch(Exception e) {e.printstacktrace (); } }}
Real-time playback of Android Audiotrack