Estou criando um programa de playback de MP3, só com PLAY e STOP, utilizando SourceDataLine.
Porém não estou encontrando a melhor forma de fazer uma seekBar, para ajustar a partir da onde tocar a música, por exemplo, a partir de 7 segundos.
public void testPlay() {
try {
File file = new File(filename);
AudioInputStream in = AudioSystem.getAudioInputStream(file);
AudioInputStream din = null;
AudioFormat baseFormat = in.getFormat();
System.out.println(baseFormat.toString());
AudioFormat decodedFormat = new AudioFormat(
AudioFormat.Encoding.PCM_SIGNED,
baseFormat.getSampleRate(),
16,
baseFormat.getChannels(),
baseFormat.getChannels() * 2,
baseFormat.getSampleRate(),
false);
din = AudioSystem.getAudioInputStream(decodedFormat, in);
// Play now.
rawplay(decodedFormat, din);
in.close();
} catch (Exception e) {
//Handle exception.
System.err.println(e.getMessage());
}
}
private void rawplay(
AudioFormat targetFormat,
AudioInputStream din)
throws IOException, LineUnavailableException {
int nInternalBufferSize = AudioSystem.NOT_SPECIFIED;
SourceDataLine line;
//line = getSourceDataLine("Alto-falantes (Dispositivo de High Definition Audio)", targetFormat, nInternalBufferSize);
line = getSourceDataLine("Java Sound Audio Engine", targetFormat, nInternalBufferSize);
// Padrão:
//SourceDataLine line = getLine(targetFormat);
o("line.getLineInfo()="+line.getLineInfo());
line.getMicrosecondPosition();
// http://download.oracle.com/javase/1.5.0/docs/guide/sound/programmer_guide/chapter4.html#113663
int bytesToRead = (int) Math.pow(2, 14);
bytesToRead = 64;
byte[] data = new byte[bytesToRead];
boolean lineStopped = false;
Control[] controls = line.getControls();
/*
for (int i = 0; i < controls.length; i++) {
o(i + "=" + controls[i].getType());
}
*/
FloatControl gainControl = (FloatControl) line.getControl(FloatControl.Type.MASTER_GAIN);
FloatControl panControl = (FloatControl) line.getControl(FloatControl.Type.PAN);
FloatControl balanceControl = (FloatControl) line.getControl(FloatControl.Type.BALANCE);
if (line != null) {
// Start
line.start();
int nBytesRead = 0;
//din.skip(500000);
while (nBytesRead != -1) {
//while (total < totalToRead) {
if (stopped) {
if (!lineStopped) {
line.stop();
//line.flush();
lineStopped = true;
}
} else {
if (lineStopped) {
line.start();
lineStopped = false;
}
gainControl.setValue(gain);
panControl.setValue(pan);
//balanceControl.setValue(balance);
nBytesRead = din.read(data, 0, bytesToRead);
if (nBytesRead == -1) {
break;
}
//o(line.getMicrosecondPosition());
//o(balance);
//o("getLevel() = " + line.getLevel());
line.write(data, 0, nBytesRead);
}
}
// Stop
line.drain();
line.stop();
line.close();
din.close();
line = null;
o("close line.");
}
}