I used the following code to get the data from a wav file on a web server. The getFormat()
, getFormatLength()
, totallength
and reading the bytes, each performed an http access and the server log showed that there are 3 accesses. Is there a way to make it one trip?
try {
audioInputStream = AudioSystem.getAudioInputStream(url);//soundFile);
format = audioInputStream.getFormat();
totallength = audioInputStream.getFrameLength()*format.getFrameSize();
waveData = new byte[(int)totallength];
int total=0;
int nBytesRead = 0;
try {
while (nBytesRead != -1 && total<totallength) {
nBytesRead = audioInputStream.read(waveData, total, (int) totallength);
if (nBytesRead>0)
total+=nBytesRead;
}
...
As it looks that you are reading first the entire file, into memory, why not reading reading all first in.
// Read the audio file into waveData:
BufferedInputStream in = new BufferedInputStream(url.openStream());
ByteArrayOutputStream bos = new ByteArrayOutputStream();
for (;;) {
int b = in.read();
if (b == -1) {
break;
}
bos.write(b);
}
in.close();
bos.close();
byte[] waveData = bos.toByteArray();
// Create the AudioInputSteam:
ByteArrayInputStream bis = new ByteArrayInputStream(waveData);
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(bis);