我正在使用声音播放器,并且我正在尝试创建一个 while 循环,该循环知道何时终止正在播放的 JFrame
。 while 循环应该在剪辑(录制)播放时循环播放并在剪辑完成后结束。但问题是:while 循环仅在打印出某些内容时才起作用,而我不希望它这样做?
import java.io.*;
import java.net.URL;
import javax.sound.sampled.*;
import javax.swing.*;
public class SoundClipTest extends JFrame {
public SoundClipTest() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
try {
// Open an audio input stream.
File soundFile = new File("Testing/recording (2).wav");
AudioInputStream audioIn = AudioSystem.getAudioInputStream(soundFile);
//URL url = new URL("http://maximumdonline.com/miscwavs/pacman.wav");
//AudioInputStream audioIn = AudioSystem.getAudioInputStream(url);
// Get a sound clip resource.
Clip clip = AudioSystem.getClip();
// Open audio clip and load samples from the audio input stream.
clip.open(audioIn);
clip.start();
this.setVisible(true);
this.setVisible(false);
boolean run = true;
//problem While Loop
while(clip.isActive()){
//Only works when I print something out during the loop:
//System.out.println(run);
}
//Test While Loop has ended.
run = false;
System.out.println(run);
//Close JFrame
} catch (UnsupportedAudioFileException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (LineUnavailableException e) {
e.printStackTrace();
}
}
注意:此声音代码大部分来自 https://www.ntu.edu.sg/home/ehchua/programming/java/J8c_PlayingSound.html 有用。我已经测试过了,但是我的 while 循环正在哭泣!
最佳答案
完成此任务的正确方法是将 LineListener
添加到 Clip
。 Clip
实现了 javax.sound.sampled.Line
接口(interface),因此我们可以使用 Line.addLineListener(LineListener)
..
Adds a listener to this line. Whenever the line's status changes, the listener's
update()
method is called with aLineEvent
object that describes the change.
关于java - While 循环在音频播放器中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37305485/