xuggle-xuggler 5.4 NullPointerException when encoding audio

225 Views Asked by At

Today I was working with the Xuggler library and I tried capturing my screen which worked flawless. But I also wanted to add audio from my microphone to the video file I captured. This was not as easy as I had expected, and now I'm stuck with this strange NullPointerException.

This is my code (abbreviated):

AudioFormat format = new AudioFormat(8000.0F, 16, 1, true, false);
writer.addAudioStream(1, 0, 1, (int) format.getSampleRate());
TargetDataLine line = getTargetDataLineForRecord(format);
final int frameSizeInBytes = format.getFrameSize();
final int bufferLengthInFrames = line.getBufferSize() / 8;
final int bufferLengthInBytes = bufferLengthInFrames * frameSizeInBytes;
final byte[] buf = new byte[bufferLengthInBytes];
final long startTime = System.nanoTime();
...
while (recording) {
    int numBytesRead = 0;
    numBytesRead = line.read(buf, 0, bufferLengthInBytes);
    int numSamplesRead = numBytesRead / 2;
    short[] audioSamples = new short[numSamplesRead];
    if (format.isBigEndian()) {
        for (int i = 0; i < numSamplesRead; i++) {
            audioSamples[i] = (short) ((buf[2 * i] << 8) | buf[2 * i + 1]);
        }
    } else {
        for (int i = 0; i < numSamplesRead; i++) {
            audioSamples[i] = (short) ((buf[2 * i + 1] << 8) | buf[2 * i]);
        }
    }
    writer.encodeAudio(1, audioSamples, System.nanoTime() - startTime, TimeUnit.NANOSECONDS); // CaptureScreen.java:118
    }
writer.close();

And here is the NullPointerException:

java.lang.NullPointerException
    at com.xuggle.mediatool.MediaWriter.encodeAudio(MediaWriter.java:923)
    at exe.media.CaptureScreen.captureScreen(CaptureScreen.java:118)
    at exe.media.CaptureScreen.main(CaptureScreen.java:43)

The problem I'm having is at this line (118):

writer.encodeAudio(1, audioSamples, System.nanoTime() - startTime, TimeUnit.NANOSECONDS);

For some reason when I try to encode the audio samples, xuggle throws a NullPointerException, I'm not sure if this is a bug or just me doing something stupid but I am unable to solve it anyway.

For better understanding I have posted all the code on pastebin and this includes code for capturing my screen and also this code where I try to record the audio.

These are the jars I have included:
commons-cli-1.2.jar
logback-classic-1.1.2.jar
logback-core-1.1.2.jar
xuggle-xuggler-arch-x86_x64-w64-mingw32.jar*
xuggle-xuggler-noarch-5.4.jar*

(The '*' means I didn't download the jar from it's primary location.

Thanks in advance and remember ANY helpful answer will be rewarded the 50 rep bounty!

1

There are 1 best solutions below

0
On

I assume that you have line.open(format); and line.start(); somewhere?

You may need to make sure that you have audiosamples: if (audioSamples.length > 0) writer.encodeAudio ...

Also, you may want to add slf4j-api-1.6.4.jar and slf4j-simple-1.6.4.jar to get more details on the errors from Xuggler.