在JAVA中.wav文件的声音在随机时间停止
我试图用java制作一个类来播放某些声音,但是声音会在随机的时刻停止,而不是在最后。它为什么这样做?提前谢谢 这是我的密码:在JAVA中.wav文件的声音在随机时间停止,java,audio,javasound,Java,Audio,Javasound,我试图用java制作一个类来播放某些声音,但是声音会在随机的时刻停止,而不是在最后。它为什么这样做?提前谢谢 这是我的密码: import java.io.File; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.Clip; import javax.sound.sampled.Line; import javax.s
import java.io.File;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.Line;
import javax.sound.sampled.LineEvent;
import javax.sound.sampled.LineListener;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
public class CoreJavaSound extends Object implements LineListener {
File soundFile;
JDialog playingDialog;
Clip clip;
public static void main(String[] args) throws Exception {
PlayBow();
}
public CoreJavaSound(String fileName) throws Exception {
JFileChooser chooser = new JFileChooser();
soundFile = new File(fileName);
System.out.println("Playing " + soundFile.getName());
Line.Info linfo = new Line.Info(Clip.class);
Line line = AudioSystem.getLine(linfo);
clip = (Clip) line;
clip.addLineListener(this);
AudioInputStream ais = AudioSystem.getAudioInputStream(soundFile);
clip.open(ais);
clip.start();
}
@Override
public void update(LineEvent le) {
LineEvent.Type type = le.getType();
if (type == LineEvent.Type.OPEN) {
System.out.println("OPEN");
} else if (type == LineEvent.Type.CLOSE) {
System.out.println("CLOSE");
System.exit(0);
} else if (type == LineEvent.Type.START) {
System.out.println("START");
playingDialog.setVisible(true);
} else if (type == LineEvent.Type.STOP) {
System.out.println("STOP");
playingDialog.setVisible(false);
clip.close();
}
}
public static void PlayBow() throws Exception
{
CoreJavaSound s = new CoreJavaSound("Bow.wav");
}
}
一切正常,除了声音在大约1秒后停止工作(文件为5秒).该剪辑是在后台线程上启动的,不是阻塞调用。它在后台播放。因此,程序将在不允许剪辑完成播放的情况下终止 试着这样做:
...
static boolean running = false;
public static void main(String[] args) throws Exception {
playBow();
while(running) {
Thread.sleep(200);
}
}
...
@Override
public void update(LineEvent le) {
LineEvent.Type type = le.getType();
if (type == LineEvent.Type.OPEN) {
running = true;
System.out.println("OPEN");
} else if (type == LineEvent.Type.CLOSE) {
System.out.println("CLOSE");
} else if (type == LineEvent.Type.START) {
System.out.println("START");
playingDialog.setVisible(true);
} else if (type == LineEvent.Type.STOP) {
System.out.println("STOP");
playingDialog.setVisible(false);
clip.close();
running = false;
}
}
请注意,此示例不是此问题的最佳解决方案。这只是一个例子。这很有效!我真傻,竟然不去想那件事:p:非常感谢!