Denis Sobolevsky Denis Sobolevsky - 3 years ago 189
Android Question

Getting NullPointer exception using Tarsos DSP in dispatcher.addAudioProcessor(p);

I use Tarsos DSP to determine frequency of the sound, that is input from microphone. It works perfectly on the majority of devices, but some of them get error.

The error:

java.lang.RuntimeException:
at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:2695)
at android.app.ActivityThread.handleLaunchActivity (ActivityThread.java:2769)
at android.app.ActivityThread.access$900 (ActivityThread.java:177)
at android.app.ActivityThread$H.handleMessage (ActivityThread.java:1430)
at android.os.Handler.dispatchMessage (Handler.java:102)
at android.os.Looper.loop (Looper.java:135)
at android.app.ActivityThread.main (ActivityThread.java:5910)
at java.lang.reflect.Method.invoke (Native Method)
at java.lang.reflect.Method.invoke (Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:1405)
at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1200)
Caused by: java.lang.NullPointerException:
at com.example.denissobolevsky.mmm.MainActivity.onCreate (MainActivity.java:1546)
at android.app.Activity.performCreate (Activity.java:6178)
at android.app.Instrumentation.callActivityOnCreate (Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:2648)


Code(line 1545-1547):

AudioProcessor p = new PitchProcessor(PitchProcessor.PitchEstimationAlgorithm.FFT_YIN, 22050, 1024, pdh);
dispatcher.addAudioProcessor(p);
new Thread(dispatcher, "Audio Dispatcher").start();


And dispatcher is:

AudioDispatcher dispatcher = AudioDispatcherFactory.fromDefaultMicrophone(22050, 1024, 0);

Answer Source

So its not simply the issue with NullPointerException which can be solved easily with checking the null value just before getting something out of the object. So by simply doing this you can get rid of this error.

if (dispatcher != null) { 
    dispatcher.addAudioProcessor(p); 
    new Thread(dispatcher, "Audio Dispatcher").start();
}

Now the next question came up is why the dispatcher became null. And hence I can give you some insight as well.

AudioDispatcher dispatcher = AudioDispatcherFactory.fromDefaultMicrophone(22050, 1024, 0);

This is the code you're using to initialize the dispatcher. The first parameter is the sample rate, then the second one indicates the buffer size and the finally the last one indicates the overlapping buffer size. So it should work perfectly in majority of device as the sampling rate you're providing is supported in majority of devices I think. The device which doesn't support the 22050 sampling rate are throwing exceptions/errors.

To get the supported sampling rate and buffer size of an Android device you might take a look at this answer of mine here.

Hope that helps. Thanks.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download