Java Sound : audio inputstream from pcm amplitude array

In this post, i am going to show the code for creating the AudioInputStream from an PCM - amplitude array. It basically converts the int [] array to byte array according to AudioFormat.

The code for the reverse operation (extract amplitude array from recorded wave file or AudioStream )is in my earlier post : http://ganeshtiwaridotcomdotnp.blogspot.com/2011/12/java-extract-amplitude-array-from.html

The code for converting PCM amplitude array to AudioStream is follows :



CODE:

    public static AudioInputStream getAudioStreamFromPCMArray(int[] audioDataIntArr, AudioFormat format) {
        byte[] data = null;
        int nlengthInSamples = audioDataIntArr.length * 2;
        if (format.getSampleSizeInBits() == 16) {
            // FIXME: debug at full length, signed/unsigned problem
            data = new byte[nlengthInSamples];
            if (format.isBigEndian()) {
                for (int i = 0; i < audioDataIntArr.length; i++) {
                    int temp = Math.abs((short) (audioDataIntArr[i] * 255));
                    data[2 * i + 1] = (byte) temp;
                    data[2 * i + 0] = (byte) (temp >> 8);
                }
            } else {
                for (int i = 0; i < audioDataIntArr.length; i++) {
                    int temp = Math.abs((short) (audioDataIntArr[i] * 255));
                    data[2 * i + 0] = (byte) temp;
                    data[2 * i + 1] = (byte) (temp >> 8);
                }
            }
        } else if (format.getSampleSizeInBits() == 8) {
            nlengthInSamples = audioDataIntArr.length;
            data = new byte[nlengthInSamples];
            if (format.getEncoding().toString().startsWith("PCM_SIGN")) {
                // PCM_SIGNED
                for (int i = 0; i < nlengthInSamples; i++) {
                    data[i] = (byte) audioDataIntArr[i];
                }
            } else {
                // PCM_UNSIGNED
                for (int i = 0; i < nlengthInSamples; i++) {
                    data[i] = (byte) (audioDataIntArr[i] + 128);
                }
            }
        }// end of if..else
        try {
            ByteArrayInputStream bais = new ByteArrayInputStream(data);
            AudioInputStream ais = new AudioInputStream(bais, format, audioDataIntArr.length);
            return ais;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
//## Required Testing -- Comments are much welcomed ...... Thanks

No comments :

Post a Comment

Your Comment and Question will help to make this blog better...