Example usage for java.nio ShortBuffer allocate

List of usage examples for java.nio ShortBuffer allocate

Introduction

In this page you can find the example usage for java.nio ShortBuffer allocate.

Prototype

public static ShortBuffer allocate(int capacity) 

Source Link

Document

Creates a short buffer based on a newly allocated short array.

Usage

From source file:net.dv8tion.jda.audio.AudioConnection.java

private byte[] encodeToOpus(byte[] rawAudio) {
    ShortBuffer nonEncodedBuffer = ShortBuffer.allocate(rawAudio.length / 2);
    ByteBuffer encoded = ByteBuffer.allocate(4096);
    for (int i = 0; i < rawAudio.length; i += 2) {
        int firstByte = (0x000000FF & rawAudio[i]); //Promotes to int and handles the fact that it was unsigned.
        int secondByte = (0x000000FF & rawAudio[i + 1]); //

        //Combines the 2 bytes into a short. Opus deals with unsigned shorts, not bytes.
        short toShort = (short) ((firstByte << 8) | secondByte);

        nonEncodedBuffer.put(toShort);/*ww  w. j  ava  2s  .co  m*/
    }
    nonEncodedBuffer.flip();

    //TODO: check for 0 / negative value for error.
    int result = Opus.INSTANCE.opus_encode(opusEncoder, nonEncodedBuffer, OPUS_FRAME_SIZE, encoded,
            encoded.capacity());

    //ENCODING STOPS HERE

    byte[] audio = new byte[result];
    encoded.get(audio);
    return audio;
}