Extends:http://blog.csdn.net/alvinhuai/article/details/8955127,http://mikespook.com/2010/11/android-%e5%ae%9e% E6%97%b6%e8%8e%b7%e5%8f%96%e9%ba%a6%e5%85%8b%e9%a3%8e%e8%be%93%e5%85%a5%e9%9f%b3%e9%87%8f%e7%9a%84%e4%bb%a3%e7 %a0%81/
A few days ago to do a recording and get the volume size of the module, today write a demo and share. If you have a better way to remind me of a message, thank you.
First, the recording function is easy to achieve, through the Audiorecord or mediarecorder can be achieved, if you want to get the recording volume, with Audiorecord more convenient. The recording function can be broadly divided into several steps. An initial recording device Audiorecord. Second, turn on a thread to realize the recording function. Three gets the audio stream of the recording to analyze its size. Four passes the size to the main thread to make the UI change accordingly.
First initialize the Audiorecord. Audiorecord (int audiosource, int samplerateinhz, int channelconfig, int audioformat, int buffersizeinbytes), initialization requires five parameters, a Udiosource refers to the recording source where we select the microphone: MediaRecorder.AudioSource.MIC. Samplerateinhz The default sampling frequency, in Hertz, the official document says 44100 is compatible with all current devices, but if you test with a simulator, there are problems, so some 8000. Channelconfig, describes the audio channel settings Channel_in_mono guaranteed to work on all devices. Audioformat Audio stream format, divided into 16bit or 8bit is currently supported by Encoding_pcm_16bit. Buffersizeinbytes The total number of audio data written to the buffer during the recording process (bytes). New audio data read from the buffer is always smaller than this value. This value is generally obtained by getminbuffersize. The parameters of the getminbuffersize can be referenced by the Audiorecord constructor. Execute the code in OnCreate.
Try{Mminibuffer=audiorecord.getminbuffersize (samplerates, Audioformat.channel_in_mono, Audioformat.encoding_pcm_16bit); if(Mminibuffer! =audiorecord.error_bad_value) {Mrecord=NewAudiorecord (MediaRecorder.AudioSource.MIC, Samplerates[i], Audioformat.channel_in_mono, Audioformat.encoding_pcm_16bit, Mminibuffer); } } Catch(IllegalArgumentException e) {; }
This is the initialization of Audiorecord, the following can be achieved recording
Public classRecordthreadextendsthread{Private BooleanMisrun =false; PublicRecordthread () {Super(); } Public voidrun () {Super. Run (); Mainactivity. This. mrecord.startrecording (); byte[] Byte_buffer =New byte[Mminibuffer]; Misrun=true; while(misrun) {intR = Mrecord.read (byte_buffer,0, Mminibuffer); intMshortarraylenght = R/2; Short[] Short_buffer =New Short[Mshortarraylenght]; Short_buffer=Bytearraytoshortarray (byte_buffer,mshortarraylenght); intMax = 0; if(R > 0){ for(inti=0; i<mshortarraylenght; i++){ if(Math.Abs (Short_buffer[i]) >max) {Max=Math.Abs (Short_buffer[i]); }} Bundle Mbundle=NewBundle (); Mbundle.putint (Msenddata, Max); Message MSG=NewMessage (); Msg.what=recordstate; Msg.setdata (Mbundle); Mhandler.sendmessage (MSG); }} mainactivity. This. Mrecord.stop (); Mhandler.sendemptymessage (Nullbuffer); } Public voidStoprecord () {Misrun=false; } }
Here is write a thread to implement the recording function. Byte_buffer Save the recorded audio stream, because there are a lot of recordings, I temporarily use the maximum value of each recording as the volume of the recording, and then return the maximum value to the main thread by handler. If you need to stop this thread you can call this thread function Stoprecord (); We can then use the OnDraw function of the view to draw the volume changes dynamically by the volume value we get each time. The specific code is not all put out, the main talk about this idea. If someone needs to be able to leave a message to me directly, can send to everybody.
Public classBoschaudioclientextendsThread {Static Final intfrequency = 44100; Static Final intChannelconfiguration =Audioformat.channel_configuration_mono; Static Final intAudioencoding =Audioformat.encoding_pcm_16bit; Private Final intSocketvol = 2000; Private Final intCycle = 8; protectedAudiorecord M_in_rec; protected intm_in_buf_size; protected byte[] m_in_bytes; protected Booleanm_keep_running; protectedlinkedlist<byte[]>m_in_q; Private intVoltime = 0; Private BooleanFlagvol =false; Publicaudioclient () {m_in_buf_size=audiorecord.getminbuffersize (Frequency, channelconfiguration, audioencoding)* 2; M_in_rec=NewAudiorecord (MediaRecorder.AudioSource.MIC,8000, Channelconfiguration, audioencoding, m_in_buf_size); M_in_bytes=New byte[M_in_buf_size]; M_keep_running=true; M_in_q=Newlinkedlist<byte[]>(); } Public voidrun () {Try { byte[] bytes_pkg; M_in_rec.startrecording (); while(m_keep_running) {//getting data from memory intR = M_in_rec.read (m_in_bytes, 0, m_in_buf_size); Bytes_pkg=M_in_bytes.clone (); //Send socket Data if(M_in_q.size () >= 2) { byte[] Buff =M_in_q.removefirst (); ByteString Socketstr=bytestring.copyfrom (Buff); } //Volume intMaxvol =Getvolumemax (R, bytes_pkg);//int v = getvolume (R, bytes_pkg); //if the volume is greater than the minimum turn on switch if(Maxvol >Socketvol) {Flagvol=true; } //If the switch is on, start timing, time about 1 cycles, turn off switch, stop timing, stop sending data if(Flagvol) {m_in_q.add (bytes_pkg); Voltime++; if((voltime/cycle) > 0) {Flagvol=false; Voltime= 0; }}} m_in_rec.stop (); M_in_rec=NULL; M_in_bytes=NULL; } Catch(Exception e) {e.printstacktrace (); } } Private intGetvolume (intRbyte[] bytes_pkg) { //The 1 intv = 0;//takes the buffer contents out, squares and operations for(byteabytes_pkg:bytes_pkg) { //There is no optimization of operations here, in order to show the code more clearlyV + = abytes_pkg *abytes_pkg; }//the sum of squares divided by the total length of the data to get the volume size. You can obtain a white noise value and then standardize the actual sampling. //If you want to use this value to operate, it is recommended to use SendMessage to throw it, in the Handler processing. intVolume = (int) (V/(float) R); returnvolume; } Private intGetvolumemax (intRbyte[] bytes_pkg) { //The 2 intMshortarraylenght = R/2; Short[] Short_buffer =Bytearray2shortarray (bytes_pkg, mshortarraylenght); intMax = 0; if(R > 0) { for(inti = 0; i < mshortarraylenght; i++) { if(Math.Abs (Short_buffer[i]) >max) {Max=Math.Abs (Short_buffer[i]); } } } returnMax; } Private Short[] Bytearray2shortarray (byte[] Data,intitems) { Short[] RetVal =New Short[items]; for(inti = 0; i < retval.length; i++) Retval[i]= ( Short) ((Data[i * 2] & 0xff) | (Data[i * 2 + 1] & 0xff) << 8); returnRetVal; } Public voidFree () {m_keep_running=false; Try{Thread.Sleep (100); } Catch(Exception e) {log.d ("Sleep exceptions...\n", "" "); } }}
Android gets audiorecord microphone volume size and makes selective send