Nikul Rao
Nikul Rao

Reputation: 83

ByteBufferAsShortBuffer cannot be cast to java.nio.FloatBuffer

I got the following error while running project.Can anyone help me??

java.lang.ClassCastException: java.nio.ByteBufferAsShortBuffer cannot be cast to java.nio.FloatBuffer

Here is my code:

Buffer[] samples = frame.samples;
                       if (aaD.track.getChannelCount() == 1)
//For using with mono track
                        {
                            Buffer b = samples[0];
                            fb = ((ByteBuffer) b.rewind()).asFloatBuffer();//here is error
                            fb.rewind();
                            smpls = new float[fb.capacity()];
                            fb.get(smpls);
                        } 

Please help

Upvotes: 2

Views: 1376

Answers (1)

Christopher Schneider
Christopher Schneider

Reputation: 3915

So the solution was not quite as elegant as I had thought. I see why you asked. I could not find a way to do what you want to do without allocating extra memory.

This is a quick and dirty way to move the ShortBuffer to a FloatBuffer.

   public FloatBuffer fBuffer(){
        ShortBuffer sb = ShortBuffer.allocate(4);
        sb.put(new short[]{256,256,128,64});

        short[] shortArr = sb.array();  
        ByteBuffer bb = ByteBuffer.allocate(shortArr.length * 2);
        bb.asShortBuffer().put(shortArr);

        return bb.asFloatBuffer();
    }

If performance is critical and you're doing tons of these operations, it's a good idea to look at using native (C/C++) code to manipulate bytes directly or use something like Renderscript.

Upvotes: 1

Related Questions