I am working on Audiorecorder to send and receive audio over UDP. I am getting null pointer exception error. After some research, I found that some devices might not support all the sampling rates. With help of this example AudioRecord object not initializing. I have even added a class to check the possible combinations of sampling rates too. I am looking for valid set of paramters that could possibly accepted on all devices.
public class audioCall {
private static final int SAMPLE_RATE = 16000;
public audioCall throws Exception {
new Thread(){
@Override
public void run() {
int bytes_read = 0;
int bytes_sent = 0;
byte[] buf = new byte[1600];
try {
// creating socket and start recording
DatagramSocket clientSocket = new DatagramSocket();
AudioRecord audioRecorder = findAudioRecord();
audioRecorder.startRecording();
while (true){
bytes_read = audioRecorder.read(pcm_data,0,1600);
DatagramPacket sendPacket = new DatagramPacket(buf, bytes_read, serverAddress, serverPort);
Socket.send(sendPacket);
bytes_sent += bytes_read;
Thread.sleep(20,0);
}
audioRecorder.stop();
audioRecorder.release();
Socket.disconnect();
Socket.close();
return;
}
}.start();
//check for the valid sample rates
private static int[] mSampleRates = new int[] { 8000, 11025, 22050, 44100 };
public AudioRecord findAudioRecord() {
for (int rate : mSampleRates) {
for (short audioFormat : new short[] { AudioFormat.ENCODING_PCM_8BIT, AudioFormat.ENCODING_PCM_16BIT }) {
for (short channelConfig : new short[] { AudioFormat.CHANNEL_IN_MONO, AudioFormat.CHANNEL_IN_STEREO }) {
try {
Log.d(LOG_TAG, "Attempting rate " + rate + "Hz, bits: " + audioFormat + ", channel: "
+ channelConfig);
int bufferSize = AudioRecord.getMinBufferSize(rate, channelConfig, audioFormat);
if (bufferSize != AudioRecord.ERROR_BAD_VALUE && buffersize != AudioRecord.ERROR) {
// check if we can instantiate and have a success
AudioRecord recorder = new AudioRecord(MediaRecorder.AudioSource.DEFAULT, rate, channelConfig, audioFormat, bufferSize);
if (recorder.getState() == AudioRecord.STATE_INITIALIZED)
return recorder;
}
} catch (Exception e) {
Log.e(LOG_TAG, rate + "Exception, keep trying.",e);
}
}
}
}
return null;
}
}
here is my Log cat error report:
FATAL EXCEPTION: Thread-5
Process: com.example.app, PID: 27780
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.AudioRecord.startRecording()' on a null object reference
at com.example.th1go_app.ControlConnection.UDPClient$2.run(Client.java:161)
How can I proceed?