Get Microphone volume
Ho开发者_StackOverflow社区w can I get the volume of the audio stream coming in through the android microphone?
There may be a simpler way, but a method that I know would work is to use an AudioRecord
object that is configured to watch the MediaRecorder.AudioSource.MIC
audio source and record in 8-bit (AudioFormat.ENCODING_PCM_8BIT
). You would need a thread to run in the background and constantly poll the object for audio with the read()
call, which fills a given byte array with audio data from the mic.
Because you are recording in 8-bit, the max range of each audio sample would be -128 to 127 (although I may have this wrong - it could be from 0 to 256). You would have to experiment with taking either the maximum magnitude byte from the returned byte array, or perhaps the RMS average depending on your application's needs. The size of the byte array would also play a part in determining how frequently your application is able to sample the input audio volume.
If you are forced to record in 16-bit PCM, then you would have to look at the value of every other byte because each sample will span two bytes. The trick will be to know which byte to look at - I believe it should be the odd-indexed bytes returned in the byte array. Or if you want higher fidelity you could look at both bytes and you would know the output volume within the range 2^15 rather than just 2^7.
Since the byte type is signed in Java, you could simply look at every buffer[index * 2 + 1]
byte and save the largest one. This would give you the max volume detected over the given sample.
As stated in my other answer, you could also take the average of these values, depending on what you are using this number for.
精彩评论