Search code examples
javamemory-mapped-filesaudiojavasound

Jump to position in audio file using Java Sound API


I'm using a AudioInputStream to feed bytes to a SourceDataLine to play a PCM file. I want to give the user the ability to move a slider to jump to some point in the file.

Issues I'm having:

  • markSupported() returns false on my AudioInputStream. So I cannot use my initial approach to call reset() then skip() (which I already thought was kind of ugly...)
  • I would really prefer not to tear down the InputStream and create a new one just to jump to a position prior to my current mark.
  • SourceLineData.getLongFramePosition() does not seem to be very reliable... I know it has a buffer, but even if account for the bytes left in the buffer, i do not understand the behavior

I have considered using a Memory-Mapped File to feed bytes to the line that way I can jump wherever I want, but I don't want to add complexity to the function if I don't have to. Is there a good way to do this that I'm missing? also can anyone explain what the frame number returned by getLongFramePosition() actually means? is it number of frames passed through speakers (does not appear to be)?


Solution

  • The cleanest way I could come up with was to use a FileChannel to read the bytes into the SourceDataLine this way based on the user moving a slider I could determine the byte position in the file (making sure to adjust or round it to line up with a frame) and then set that position in the FileChannel and then continue playback. I flushed the line when this happened to keep from playing remaining bytes.