Example usage for java.nio ShortBuffer flip

List of usage examples for java.nio ShortBuffer flip

Introduction

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

Prototype

public final Buffer flip() 

Source Link

Document

Flips this buffer.

Usage

From source file:Main.java

public static ShortBuffer createShortBuffer(final short... data) {
    if (data == null) {
        return null;
    }/*from   w  w  w.ja v  a2 s .co  m*/
    final ShortBuffer buff = createShortBuffer(data.length);
    buff.clear();
    buff.put(data);
    buff.flip();
    return buff;
}

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);//from w  w w .ja  va 2 s.c o 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;
}