Search code examples
javafileaudiobytewav

How to convert little endian to big endian in java .wav files


I've got the following problem:

I need to convert audio bytes (byte[]) from

48kHz, 16 bit, stereo, PCM signed, BIG ENDIAN

to

48kHz, 16 bit, stereo, PCM signed, LITTLE ENDIAN

in java and save it as .wav file.

                      List<byte[]> orderedBytes = bytesFromVoice;

                            /*
                            Here i need to sort the bytes
                             */

                            int size = 0;
                            for (byte[] bs : orderedBytes) {
                                size += bs.length;
                            }
                            byte[] decodedData = new byte[size];
                            int i = 0;
                            for (byte[] bs : orderedBytes) {
                                for (int j = 0; j < bs.length; j++) {
                                    decodedData[i++] = bs[j];
                                }
                            }

                            //writing to file
                            try {
                                getWavFile(getNextFile(), decodedData);
                            } catch (IOException exception) {
                                exception.printStackTrace();
                            }

Solution

  • Found a way ... it's pretty easy:

    private void getWavFile(File outFile, byte[] decodedData) throws IOException {
        AudioFormat format = new AudioFormat(48000.0F, 16, 2, true, true);
        boolean convertable = AudioSystem.isConversionSupported(
                               new AudioFormat(48000, 16, 2, true, false), format);
        System.out.println("Can be converted: " + convertable);
        AudioSystem.write(new AudioInputStream(
            new ByteArrayInputStream(decodedData), format, decodedData.length), 
            AudioFileFormat.Type.WAVE, outFile);
        File converted = new File("converted.wav");
        try {
            AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(
                new AudioFormat(48000, 16, 2, true, false), 
                AudioSystem.getAudioInputStream(outFile));
            AudioSystem.write(audioInputStream, AudioFileFormat.Type.WAVE, converted);
        } catch (UnsupportedAudioFileException e) {
                e.printStackTrace();
        }
    }