Search code examples
javajavax.sound.sampled

Random Access on AudioInputStream java


Is there an example of randomly accessing an AudioInputStream? something like any ordinary audio player does - when you take the bar wherever you want and it plays from wherever you want, how can i access bytes in the audio stream in that manner?

something simple like that : read(byte[] buffer, long startingFrom) where startingFrom can be wherever i want in the audio stream


Solution

  • Using (simulating?) random access in an AudioInputStream is the same as in a normal InputStream. You can create a mark() at the beginning of the file, so before any calls to read() have been done. Then, when you want to do random access, you stop reading from the stream, go to the marker position by calling reset() and then use skip() to go to the location you desire.

    Note that the initial 'mark' will default to 0 for an AudioInputStream, so the initial call is not needed. However this behavior is not specified so it might change in the future.

    The implementation of AudioInputStream (Oracle Java 8) supports this mechanism if the underlying stream (for instance the InputStream you give to the constructor) supports it. You can find if the AudioInputStream supports it by calling markSupported().

    Unfortunately when using the utility functions from AudioSystem to create the AudioInputStream you can't influence the underlying stream. It could even differ per platform. If your stream does not support it (or you want to be absolutely sure it does support it) you could create a new AudioInputStream by wrapping one in a BufferedInputStream. For example like this:

    AudioInputStream normalStream = AudioSystem.getAudioInputStream(...);
    AudioInputStream bufferedStream = new AudioInputStream(new BufferedInputStream(normalStream),
                                        normalStream.getFormat(), AudioSystem.NOT_SPECIFIED);
    

    Disclaimer: I would qualify this has a 'hack' to create random access. To my surprise I could find little about simulating random access using the mark/reset mechanism in InputStream. This might be because there is a caveat to it. Edit: John Skeet agrees with me on this approach.