Java Byte Array to Short byteToShort(byte[] data, int length, boolean reduceStereo)

Here you can find the source of byteToShort(byte[] data, int length, boolean reduceStereo)

Description

Converts audio data in 'byte' format (little-endian 16-bit) to short array

License

Open Source License

Parameter

Parameter Description
data Data
length Number of bytes to actually use
reduceStereo If true, reduces stereo data to become mono

Return

Short version of data

Declaration

public static short[] byteToShort(byte[] data, int length, boolean reduceStereo) 

Method Source Code

//package com.java2s;
/*/*  ww  w .  j ava  2s.com*/
Copyright 2009 The Open University
http://www.open.ac.uk/lts/projects/audioapplets/
    
This file is part of the "Open University audio applets" project.
    
The "Open University audio applets" project is free software: you can
redistribute it and/or modify it under the terms of the GNU General Public
License as published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
    
The "Open University audio applets" project is distributed in the hope that it
will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.
    
You should have received a copy of the GNU General Public License
along with the "Open University audio applets" project.
If not, see <http://www.gnu.org/licenses/>.
*/

public class Main {
    /**
     * Converts audio data in 'byte' format (little-endian 16-bit) to short array
     * @param data Data
     * @param length Number of bytes to actually use
     * @param reduceStereo If true, reduces stereo data to become mono
     * @return Short version of data
     */
    public static short[] byteToShort(byte[] data, int length, boolean reduceStereo) {
        if (reduceStereo) {
            short[] shortData = new short[length / 4];
            for (int i = 0; i < shortData.length; i++) {
                short val1 = (short) ((data[i * 4 + 1] << 8) | (data[i * 4] & 0xff));
                short val2 = (short) ((data[i * 4 + 3] << 8) | (data[i * 4 + 2] & 0xff));
                shortData[i] = (short) (((int) val1 + (int) val2) / 2);
            }
            return shortData;
        } else {
            short[] shortData = new short[length / 2];
            for (int i = 0; i < shortData.length; i++) {
                shortData[i] = (short) ((data[i * 2 + 1] << 8) | (data[i * 2] & 0xff));
            }
            return shortData;
        }
    }
}

Related

  1. bytesToShorts(byte byteBuffer[])
  2. bytesToShorts(byte[] byteData)
  3. bytesToShorts(byte[] src, int srcPos, short[] dest, int destPos, int length, boolean bigEndian)
  4. byteToShort(byte[] b)
  5. byteToShort(byte[] byteData, boolean writeLittleEndian)