简体   繁体   中英

Java - converting byte array of audio into integer array

I need to pass audio data into a 3rd party system as a "16bit integer array" (from the limited documentation I have).

This is what I've tried so far (the system reads it in from the resulting bytes.dat file).

    AudioInputStream inputStream = AudioSystem.getAudioInputStream(new File("c:\\all.wav"));
    int numBytes = inputStream.available();
    byte[] buffer = new byte[numBytes];
    inputStream.read(buffer, 0, numBytes);

    BufferedWriter fileOut = new BufferedWriter(new FileWriter(new File("c:\\temp\\bytes.dat")));

    ByteBuffer bb = ByteBuffer.wrap(buffer);

    while (bb.remaining() > 1) {
        short current = bb.getShort();
        fileOut.write(String.valueOf(current));
        fileOut.newLine();
    }

This doesn't seem to work - the 3rd party system doesn't recognise it and I also can't import the file into Audacity as raw audio.

Is there anything obvious I'm doing wrong, or is there a better way to do it?

Extra info: the wave file is 16bit, 44100Hz, mono.

Edit 2: I rarely use AudioInputStream but the way you write out the raw data seems to be rather complicated. A file is just a bunch of subsequent bytes so you could write your audio byte array with one single FileOutputStream.write() call. The system might use big endian format whereas the WAV file is stored in little endian (?). Then your audio might play but extremely silently for example.

Edit 3

Removed the code sample.

Is there a reason you are writing the audio bytes as strings into the file with newlines? I would think the system expects the audio data in binary format, not in string format.

I've just managed to sort this out.

I had to add this line after creating the ByteBuffer.

bb.order(ByteOrder.LITTLE_ENDIAN);
AudioFileFormat audioFileFormat;
try {
    File file = new File("path/to/wav/file");
    audioFileFormat = AudioSystem.getAudioFileFormat(file);
    int intervalMSec = 10; // 20 or 30
    byte[] buffer = new byte[160]; // 320 or 480.
    AudioInputStream audioInputStream = new AudioInputStream(new FileInputStream(file),
            audioFileFormat.getFormat(), (long) audioFileFormat.getFrameLength());
    int off = 0;
    while (audioInputStream.available() > 0) {
        audioInputStream.read(buffer, off, 160);
        off += 160;
        intervalMSec += 10;
        ByteBuffer wrap = ByteBuffer.wrap(buffer);
        int[] array = wrap.asIntBuffer().array();
    }
    audioInputStream.close();
} catch (UnsupportedAudioFileException | IOException e) {
    e.printStackTrace();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM