Converts bytes to doubles (from -1.0 to 1.0) according to audio format - Java javax.sound.sampled

Java examples for javax.sound.sampled:Audio

Description

Converts bytes to doubles (from -1.0 to 1.0) according to audio format

Demo Code


//package com.java2s;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import javax.sound.sampled.AudioFormat;

public class Main {
    /**/*from www  .j  a v a  2  s . co m*/
     * Converts bytes to doubles (from -1.0 to 1.0) according to format
     */
    public static void bytesToDoubles(AudioFormat format, byte[] source,
            int sourcePos, int sourceLen, double[] target, int targetPos) {
        if (format.getSampleSizeInBits() == 16) {
            ByteBuffer bb = ByteBuffer.wrap(source);
            if (format.isBigEndian())
                bb.order(ByteOrder.BIG_ENDIAN);
            else
                bb.order(ByteOrder.LITTLE_ENDIAN);
            for (int i = 0; i < sourceLen / 2; i++) {
                short val = bb.getShort(i * 2 + sourcePos);
                double dval = ((double) val) / (double) Short.MAX_VALUE;
                target[i + targetPos] = dval;
            }
        } else if (format.getSampleSizeInBits() == 8) {
            for (int i = 0; i < sourceLen; i++) {
                double dval = ((double) source[i + sourcePos])
                        / (double) Byte.MAX_VALUE;
                target[i + targetPos] = dval;
            }
        }
    }
}

Related Tutorials