I am trying to buffer audio data to analyze the decibel level.
I am using the AudioRecord class, since it allows to process the data right away from a buffer without storing them in a file.
I am using the
<uses-permission android:name="ANDROID.PERMISSION.RECORD_AUDIO" />
permission. Edit: This is wrong!
I am launching it as a service from my main activity in onStart()
with
Intent intent = new Intent(this, Audio2.class);
startService(intent);
The service calls findAudioRecord()
during onStartCommand(...)
.
private int[] sampleRates = new int[] { 44_100, 22_050, 11_025, 8_000 };
private short[] audioFormats = new short[] { AudioFormat.ENCODING_PCM_16BIT, AudioFormat.ENCODING_PCM_8BIT };
private short[] channelConfigs = new short[] { AudioFormat.CHANNEL_IN_MONO, AudioFormat.CHANNEL_IN_STEREO };
public AudioRecord findAudioRecord() {
for (int rate : sampleRates){
for (short audioFormat : audioFormats){
for (short channelConfig : channelConfigs){
try {
Log.d(TAG, "Attempting rate " + rate + "Hz, " + audioFormat + " bits, channel: " + channelConfig);
bufferSize = AudioRecord.getMinBufferSize(rate, channelConfig, audioFormat);
if (bufferSize != AudioRecord.ERROR_BAD_VALUE) {
AudioRecord recorder = new AudioRecord(MediaRecorder.AudioSource.DEFAULT, rate, channelConfig, audioFormat, bufferSize*10);
if (recorder.getState() == AudioRecord.STATE_INITIALIZED) {
return recorder;
} else {
recorder.release();
}
}
} catch (Exception e) {
Log.e(TAG, rate + "Exception, keep trying.",e);
}
}
}
}
Log.wtf(TAG, "No working configuration found!");
return null;
}
This allways returns null. I get the error:
E/AudioRecord﹕ AudioFlinger could not create record track, status: -1
E/AudioRecord-JNI﹕ Error creating AudioRecord instance: initialization check failed.
E/AudioRecord-Java﹕ android.media.AudioRecord Error code -20 when initializing native AudioRecord object.
I am using a Samsung Galaxy S4.
What I have tried without success:
After a lot of hours, I finally figured out the problem. If you use the autocomplete feature of Android Studio and type
<uses-permission android:name="RECORD_AUDIO" />
followed by enter, Android Studio will fill in
<uses-permission android:name="ANDROID.PERMISSION.RECORD_AUDIO" />
This, however does not work, since case apparently matters. No warnings, nothing. After I changed it to
<uses-permission android:name="android.permission.RECORD_AUDIO" />
it finally worked...