public boolean load(File file) { this.file = file; if (file != null && file.isFile()) { try { errStr = null; audioInputStream = AudioSystem.getAudioInputStream(file); fileName = file.getName(); format = audioInputStream.getFormat(); } catch (Exception ex) { reportStatus(ex.toString()); return false; } } else { reportStatus("Audio file required."); return false; } numChannels = format.getChannels(); sampleRate = (double) format.getSampleRate(); sampleBitSize = format.getSampleSizeInBits(); long frameLength = audioInputStream.getFrameLength(); long milliseconds = (long) ((frameLength * 1000) / audioInputStream.getFormat().getFrameRate()); double audioFileDuration = milliseconds / 1000.0; if (audioFileDuration > MAX_AUDIO_DURATION) duration = MAX_AUDIO_DURATION; else duration = audioFileDuration; frameLength = (int) Math.floor((duration / audioFileDuration) * (double) frameLength); try { audioBytes = new byte[(int) frameLength * format.getFrameSize()]; audioInputStream.read(audioBytes); } catch (Exception ex) { reportStatus(ex.toString()); return false; } getAudioData(); return true; }
private void getAudioData() { if (format.getSampleSizeInBits() == 16) { nlengthInSamples = audioBytes.length / 2; audioData = new int[nlengthInSamples]; if (format.isBigEndian()) { for (int i = 0; i < nlengthInSamples; i++) { // First byte is MSB (high order) int MSB = (int) audioBytes[2 * i]; // Second byte is LSB (low order) int LSB = (int) audioBytes[2 * i + 1]; audioData[i] = MSB << 8 | (255 & LSB); } } else { for (int i = 0; i < nlengthInSamples; i++) { // First byte is LSB (low order) int LSB = (int) audioBytes[2 * i]; // Second byte is MSB (high order) int MSB = (int) audioBytes[2 * i + 1]; audioData[i] = MSB << 8 | (255 & LSB); } } } else { if (format.getSampleSizeInBits() == 8) { nlengthInSamples = audioBytes.length; audioData = new int[nlengthInSamples]; if (format.getEncoding().toString().startsWith("PCM_SIGN")) { for (int i = 0; i < audioBytes.length; i++) { audioData[i] = audioBytes[i]; } } else { for (int i = 0; i < audioBytes.length; i++) { audioData[i] = audioBytes[i] - 128; } } } } }