Reputation: 440
So, I have an AudioInputStream
, which reads from a FileInputStream
. I want to close the FileInputStream
which will close the AudioInputStream
.
Is there any way to load the audio completely, so that I don't have to stream it directly from the file?
Upvotes: 1
Views: 100
Reputation: 40
You can store it in a Java Clip
.
Example:
Clip clip = AudioSystem.getClip();
clip.open(/*your AudioInputStream*/);
Make clip a field, to use it later.
Upvotes: 1
Reputation: 37845
If you want an AudioInputStream
, you can load the entire file in to a byte array:
static AudioInputStream load(File file) throws IOException {
try (FileInputStream in = new FileInputStream(file)) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
byte[] buf = new byte[4096];
for (int b; (b = in.read(buf)) > -1;) {
bytes.write(buf, 0, b);
}
return AudioSystem.getAudioInputStream(
new ByteArrayInputStream(bytes.toByteArray());
}
}
Or in Java 7:
static AudioInputStream load(File file) throws IOException {
return AudioSystem.getAudioInputStream(
new ByteArrayInputStream(Files.readAllBytes(file.toPath()));
}
Upvotes: 0