// Copyright 2014-2025 Jesper Larsson
//
// This file is part of Klipspringer, <https://klipspringer.avadeaux.net/>
//
// Klipspringer is free software: you can redistribute it and/or modify it under the terms of the
// GNU General Public License as published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// Klipspringer is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
// even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License along with Klipspringer. If
// not, see <https://www.gnu.org/licenses/>.
import java.io.File;
import java.io.IOException;
import javax.sound.sampled.*;
/** Demonstration of seeking in a FLAC or Ogg Vorbis AudioInputStream by using mark and reset. May
* or may not not work with other file formats. Compile and run example:
* <pre>
* javac examples/PlaySPIWithSeeking.java
* java -cp examples:lib/klipcodec.jar --enable-native-access=ALL-UNNAMED -Djava.library.path=lib PlaySPIWithSeeking some_audio_file.flac
* </pre>
*/
class PlaySPIWithSeeking {
private static void playSeconds(AudioInputStream stream, SourceDataLine line, double seconds) throws IOException {
AudioFormat format = stream.getFormat();
byte[] b = new byte[1024 * format.getFrameSize()];
long bytes = (long) (seconds * format.getSampleRate() * format.getFrameSize());
while (bytes > 0) {
int n = (int) Math.min(bytes, b.length);
n = stream.read(b, 0, n);
if (n < 0) { break; }
line.write(b, 0, n);
bytes -= n;
}
}
public static void main(String[] args) throws Exception {
if (args.length != 1) {
System.err.println("Expecting file argument");
System.exit(1);
}
AudioInputStream stream = AudioSystem.getAudioInputStream(new File(args[0]));
AudioFormat format = stream.getFormat();
SourceDataLine line = AudioSystem.getSourceDataLine(format);
line.open();
line.start();
System.out.println("Playing 5 seconds starting 20 seconds into the file");
stream.skip(20 * (long) (format.getSampleRate()*format.getFrameSize()));
playSeconds(stream, line, 5);
System.out.println("Playing 3 seconds from the start of the file");
stream.reset();
playSeconds(stream, line, 3);
System.out.println("Playing the next 3 seconds");
stream.mark(0);
playSeconds(stream, line, 3);
System.out.println("Skipping 20 seconds ahead and playing 5 seconds");
stream.skip(20 * (long) (format.getSampleRate()*format.getFrameSize()));
playSeconds(stream, line, 5);
System.out.println("Going back to 3 seconds into the file and playing 5 seconds again");
stream.reset();
playSeconds(stream, line, 5);
stream.close();
line.drain();
}
}
Version: v4.3.2.2 (2026-05-16T17:03:34+02:00)
Raw file
Source code overview
Klipspringer home