In Java, we can play audio like this:

audioInputStream = AudioSystem.getAudioInputStream(audio);
AudioFormat audioFormat = audioInputStream.getFormat();
DataLine.Info info = new Info(SourceDataLine.class, audioFormat);
sourceDataLine = (SourceDataLine) AudioSystem.getLine(info);
byte[] buf = new byte[0xFF];
int onceReadDataSize = 0;

// look at here
while ((onceReadDataSize = audioInputStream
     .read(buf, 0, buf.length)) != -1)
  sourceDataLine.write(buf, 0, onceReadDataSize);

Seems that we can play audio by doing some initializations and create a loop that continuously do sourceDataLine.write.
So, I think I can implement pause/resume by changing the last few lines to:

// look at here
while (true) {
  if (!paused)sourceDataLine.write(buf, 0, onceReadDataSize);
  onceReadDataSize = audioInputStream.read(buf, 0, buf.length);
  if (onceReadDataSize == -1) break;

But it doesn't work -- it just stop when I set paused to true in another thread, and when I set it back to false, it doesn't resume.

Is there any workarounds? Or is there any alternative Java audio library?

  • \$\begingroup\$ Why nobody's answering my question? Such low view makes me worried... \$\endgroup\$ – ice1000 Dec 6 '17 at 1:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.