1

I'm trying to convert a file with a .wav extension to a double array but I am getting an error:

09-15 05:09:47.222 22358-22358/com.R1100.bluetooth D/R1100Err: unsupported audio format: '/storage/emulated/0/HeartSounds/a0002.wav'

The file really is a .wav but I have no idea why this happens.

Here is the method I used:

public static double[] read(String filename) {
    byte[] data = readByte(filename);
    int n = data.length;
    double[] d = new double[n/2];
    for (int i = 0; i < n/2; i++) {
        d[i] = ((short) (((data[2*i+1] & 0xFF) << 8) + (data[2*i] & 0xFF))) / ((double) MAX_16_BIT);
    }
    return d;
}

// return data as a byte array
private static byte[] readByte(String filename) {
    byte[] data = null;
    AudioInputStream ais = null;
    try {

        // try to read from file
        File file = new File(filename);
        if (file.exists()) {
            ais = AudioSystem.getAudioInputStream(file);
            int bytesToRead = ais.available();
            data = new byte[bytesToRead];
            int bytesRead = ais.read(data);
            if (bytesToRead != bytesRead)
                throw new IllegalStateException("read only " + bytesRead + " of " + bytesToRead + " bytes");
        }

        // try to read from URL
        else {
            URL url = Wav.class.getResource(filename);
            ais = AudioSystem.getAudioInputStream(url);
            int bytesToRead = ais.available();
            data = new byte[bytesToRead];
            int bytesRead = ais.read(data);
            if (bytesToRead != bytesRead)
                throw new IllegalStateException("read only " + bytesRead + " of " + bytesToRead + " bytes");
        }
    }
    catch (IOException e) {
        throw new IllegalArgumentException("could not read '" + filename + "'", e);
    }

    catch (UnsupportedAudioFileException e) {
        throw new IllegalArgumentException("unsupported audio format: '" + filename + "'", e);
    }

    return data;
}

Thanks.

0xCursor
  • 2,242
  • 4
  • 15
  • 33
R1100
  • 11
  • 3
  • 1
    Wav doesn't mean Java can definitely read the audio. Wav is just a container, and can contain more or less any type of encoding, even mp3. You will need to find out what encoding the file actually uses. (But it's probably something Java can't decode.) – Radiodef Sep 15 '18 at 01:14
  • Also see https://stackoverflow.com/questions/11104118/javax-sound-sampled-unsupportedaudiofileexception-could-not-get-audio-input-str (probably duplicate) – Radiodef Sep 15 '18 at 01:25

0 Answers0