1

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?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Mrab Ezreb
  • 440
  • 5
  • 15
  • 1
    Audio files can be really big - are you sure you want to cache it in RAM? – Ron Kuper May 19 '15 at 14:56
  • yes, I am making a library to manage assets, and I already have it set up to load the asset from a file, then close the fileinputstream. Image files can also be very big, and I do the same thing with them. – Mrab Ezreb May 19 '15 at 14:57
  • 1
    Youu can read the file into memory and then create a ByteArrayInputStream on top of the memory buffer and play audio from that. – Ron Kuper May 19 '15 at 14:58
  • I think that while I was looking around, I found an idea something like that. The only issue is that it doesn't keep the format information, so it will throw an unsupported audio exception. – Mrab Ezreb May 19 '15 at 14:59
  • 2
    You are providing information that is relevant to your question within comments. Don't do that; instead update your question. – GhostCat May 19 '15 at 15:00
  • @Mrab Ezreb just specify the format yourself using the apropriate constructor: http://docs.oracle.com/javase/7/docs/api/javax/sound/sampled/AudioInputStream.html#AudioInputStream(java.io.InputStream,%20javax.sound.sampled.AudioFormat,%20long) – ortis May 19 '15 at 15:00
  • alright, I will try that. – Mrab Ezreb May 19 '15 at 15:01

2 Answers2

1

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.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Steffen E
  • 40
  • 9
  • man, am I dumb. I knew about clips, but I never thought to use them. Thanks a lot. can't quite accept this answer yet – Mrab Ezreb May 19 '15 at 15:05
0

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()));
}
Radiodef
  • 37,180
  • 14
  • 90
  • 125