我有一个 wav 音频文件。我知道如何在 java 中使用 AudioImputStream 播放它。我学会了创建一个jslider。现在我必须将滑块用作带有音频的进度条,例如播放音频,因此滑块会向前移动。如果用户改变了滑块的位置,音频文件必须从那个位置开始播放。
我是 Java 新手,我可能在帖子中犯了一些错误。请忽略它们
因此,当滑块更新时,我一直在更新音轨。我尝试将 changeListner 添加到滑块,但我无法让它工作。
这是代码
import java.io.File;
import java.util.Timer;
import java.util.TimerTask;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.swing.JFrame;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class audio {
public static void main(String args[])
{
try {
final JFrame f=new JFrame();
File yourFile;
AudioInputStream stream;
AudioFormat format;
DataLine.Info info;
final Clip clip;
yourFile = new File(fileName);
stream = AudioSystem.getAudioInputStream(yourFile);
format = stream.getFormat();
final long frames =stream.getFrameLength();
final double durationInSeconds = (frames+0.0) / format.getFrameRate();
final JSlider slider=new JSlider(0,(int) Math.round(durationInSeconds),0);
info = new DataLine.Info(Clip.class, format);
clip = (Clip) AudioSystem.getLine(info);
clip.open(stream);
clip.start();
f.add(slider);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
TimerTask timerTask=new TimerTask(){
@Override
public void run() {
// TODO Auto-generated method stub
{
double timeNow=(durationInSeconds*clip.getFramePosition())/frames;
slider.setValue((int)Math.round(timeNow));
f.repaint();
}
}
};
Timer timer = new Timer("MyTimer");//create a new Timer
timer.scheduleAtFixedRate(timerTask, 30, 30);//this line starts the timer at the same time its executed
}
catch (Exception e) {
System.out.println(e);
}
}
}