Search code examples
androidlibgdxbyte

ByteBuffer from short to byte[]


I let the user record a short snippet of sound. It´s stored as short[]

final int samples = 44100;
boolean isMono = true;
final short[] data = new short[samples * 5];
final AudioRecorder recorder = Gdx.audio.newAudioRecorder(samples, isMono);
final AudioDevice player = Gdx.audio.newAudioDevice(samples, isMono);
ByteBuffer buffer;

start to record:

public void startRecord(){
    new Thread(new Runnable() {
        @Override
        public void run() {
                System.out.println("Record start:");
                recorder.read(data, 0, data.length);
                recorder.dispose();
                //buffer.putShort(data[1]);
                System.out.println("Record ended:");
            }

    }).start();
}

And play the recorded sound:

public void playRecorded(){
    new Thread(new Runnable() {
        @Override
        public void run() {
            player.writeSamples(data, 0, data.length);
            player.dispose();

        }
    }).start();
}

I now need to store their audio snippet in filehandle. And to do so I need to convert it to byte[] from what I know.


Solution

  • Try this

    ByteBuffer buffer = ByteBuffer.allocate(2);
    buffer.putShort(short_value);
    return buffer.array();