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

Java examples for javax.sound.sampled:Audio

Description

Converts doubles (from -1.0 to 1.0) to bytes 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  w  w  w .j a  va  2s. com*/
     * Converts doubles (from -1.0 to 1.0) to bytes according to format
     */
    public static void doublesToBytes(AudioFormat format, double[] source,
            int sourcePos, int sourceLen, byte[] target, int targetPos) {
        if (format.getSampleSizeInBits() == 16) {
            ByteBuffer bb = ByteBuffer.wrap(target);
            if (format.isBigEndian())
                bb.order(ByteOrder.BIG_ENDIAN);
            else
                bb.order(ByteOrder.LITTLE_ENDIAN);
            for (int i = 0; i < sourceLen; i++) {
                double val = source[i + sourcePos];
                short sval = (short) (val * Short.MAX_VALUE);
                bb.putShort(targetPos + i * 2, sval);
            }
        } else if (format.getSampleSizeInBits() == 8) {
            for (int i = 0; i < sourceLen; i++) {
                double val = source[i + sourcePos];
                byte bval = (byte) (val * Byte.MAX_VALUE);
                target[targetPos + i] = bval;
            }
        }
    }
}

Related Tutorials