我一直在关注一些教程并在这里阅读类似的线程但是因为我正在使用FXML,所以我很难代表同样的事情。
所以,基本上我正试图在timeText上每秒更新一次所用的时间。
任何人都可以指出我正确的方向如何做到这一点。
下面,您可以看到我的控制器类的代码。记住,我也创建了自己的队列。
主要
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
public class Main extends Application {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
//Application.launch(Main.class, (java.lang.String[])null);
launch(args);
}
@Override
public void start(Stage primaryStage) {
try {
AnchorPane page = (AnchorPane) FXMLLoader.load(Main.class.getResource("musicPlayer.fxml"));
Scene scene = new Scene(page);
primaryStage.setScene(scene);
primaryStage.setTitle("FXML is Simple");
scene.getStylesheets().add(getClass().getResource("css.css").toExternalForm());
primaryStage.initStyle(StageStyle.UNDECORATED);
primaryStage.show();
} catch (Exception ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
控制器
public class graphicalController implements Initializable
{
//GUI Decleration
public Button centreButton;
public Button backButton;
public Button forwardButton;
public ToggleButton muteToggle;
public MenuItem loadFolder;
public Text nameText;
public Text albumText;
public Text timeText;
public Text artistText;
public Slider timeSlider;
public Slider volumeSlider;
//Controller Decleration
String absolutePath;
SongQueue q = new SongQueue();
MediaPlayer player;
Status status;
boolean isPlaying = false;
boolean isMuted = false;
boolean isPaused = false;
private Duration duration;
@Override
public void initialize(URL location, ResourceBundle resources)
{
centreButton.setStyle("-fx-background-image: url('/Resources/Play_Button.png')");
centreButton.setText("");
backButton.setStyle("-fx-background-image: url('/Resources/Back_Button.png')");
backButton.setText("");
forwardButton.setStyle("-fx-background-image: url('/Resources/Forward_Button.png')");
forwardButton.setText("");
muteToggle.setStyle("-fx-background-image: url('/Resources/ToggleSound_Button.png')");
muteToggle.setText("");
nameText.setText("");
albumText.setText("");
artistText.setText("");
}
public void handlecentreButtonClick() {
if(isPlaying)
{
player.pause();
centreButton.setStyle("-fx-background-image: url('/Resources/Play_Button.png')");
isPaused = true;
isPlaying = false;
}
else if(!(q.isEmpty())) {
if(isPaused)
{
player.play();
centreButton.setStyle("-fx-background-image: url('/Resources/Pause_Button.png')");
}
else{
String file = q.peek().fileName.toString();
String path = absolutePath + "\\" + file;
Media song = new Media(new File(path).toURI().toString());
player = new MediaPlayer(song);
player.setVolume(volumeSlider.getValue() / 100);
player.play();
centreButton.setStyle("-fx-background-image: url('/Resources/Pause_Button.png')");
}
isPlaying = true;
}
setSongText();
}
public void handleforwardButtonClick() {
player.stop();
Song currentSong = q.peek();
q.push(currentSong);
q.pop();
String file = q.peek().fileName.toString();
String path = absolutePath + "\\" + file;
Media song = new Media(new File(path).toURI().toString());
player = new MediaPlayer(song);
if(isPlaying) {
player.play();
}
setSongText();
}
public void handlebackButtonClick() {
player.stop();
File folder = new File(absolutePath);
File[] listOfFiles = folder.listFiles();
int listLength = listOfFiles.length;
for (int k = 0; k < listLength-1; k++) {
Song currentSong = q.peek();
q.push(currentSong);
q.pop();
}
String file = q.peek().fileName.toString();
String path = absolutePath + "\\" + file;
Media song = new Media(new File(path).toURI().toString());
player = new MediaPlayer(song);
if(isPlaying) {
player.play();
}
setSongText();
}
public void handleLoadButtonClick() {
DirectoryChooser directoryChooser = new DirectoryChooser();
File selectedDirectory = directoryChooser.showDialog(null);
absolutePath = selectedDirectory.getAbsolutePath();
String path = absolutePath;
loadFilesFromFolder(path);
}
public void handleVolumeSlider() {
try {
player.setVolume(volumeSlider.getValue() / 100);
} catch (Exception b) {}
}
public void handleVolumeMute() {
try{
if(isMuted)
{
player.setVolume(volumeSlider.getValue() / 100);
isMuted = false;
}
else
{
player.setVolume(0);
isMuted = true;
}
} catch (Exception a) {}
}
public void loadFilesFromFolder(String path) {
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
while(!(q.isEmpty()))
{
try {Thread.sleep(500);}catch (Exception e){}
Song j = q.pop();
}
int listLength = listOfFiles.length;
for (int k = 0; k < listLength; k++) {
if (listOfFiles[k].isFile()) {
String fileName = listOfFiles[k].getName();
String fileNamePath = path + "\\" +fileName;
try {
InputStream input = new FileInputStream(new File(fileNamePath));
ContentHandler handler = new DefaultHandler();
Metadata metadata = new Metadata();
Parser parser = new Mp3Parser();
ParseContext parseCtx = new ParseContext();
parser.parse(input, handler, metadata, parseCtx);
input.close();
String songName = metadata.get("title");
String artistName = metadata.get("xmpDM:artist");
String albumName = metadata.get("xmpDM:genre");
int id = k + 1;
Song newSong = new Song(id, fileName, songName, artistName, albumName);
q.push(newSong);
setSongText();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (TikaException e) {
e.printStackTrace();
}
}
}
}
public void setSongText() {
// String file = q.peek().fileName.toString();
// String song = q.peek().songName.toString();
// String artist = q.peek().artistName.toString();
// String album = q.peek().albumName.toString();
try {
String file = q.peek().fileName.toString();
String path = absolutePath + "\\" + file;
InputStream input = new FileInputStream(new File(path));
ContentHandler handler = new DefaultHandler();
Metadata metadata = new Metadata();
Parser parser = new Mp3Parser();
ParseContext parseCtx = new ParseContext();
parser.parse(input, handler, metadata, parseCtx);
input.close();
String songName = metadata.get("title");
String artistName = metadata.get("xmpDM:artist");
String albumName = metadata.get("xmpDM:genre");
nameText.setText(songName);
albumText.setText(albumName);
artistText.setText(artistName);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (TikaException e) {
e.printStackTrace();
}
}
protected void updateValues() {
if (timeText != null && timeSlider != null && duration != null) {
Platform.runLater(new Runnable() {
public void run() {
Duration currentTime = player.getCurrentTime();
timeText.setText(formatTime(currentTime, duration));
timeSlider.setDisable(duration.isUnknown());
if (!timeSlider.isDisabled() && duration.greaterThan(Duration.ZERO) && !timeSlider.isValueChanging()) {
timeSlider.setValue(currentTime.divide(duration).toMillis() * 100.0);
}
}
});
}
}
}
}
答案 0 :(得分:0)
关于每秒更新经过时间的时间,我使用了一个每秒循环的线程来检测这个变化。您可以在下面看到我用于此的代码:
/**
* Program thread: Run
* Description: Cycles every second (998 Milliseconds) to detect a change in time for song. Values on GUI are updated accordinly.
*/
new Thread(new Runnable() {
@Override
public void run() {
while(true)
{
if(isPlaying) {
currentTime = player.getCurrentTime();
totalTime = player.getMedia().getDuration();
updateTimeValues();
updateTimeSlider();
if(totalTimeText.equals(currentTimeText))
{
if(isLooping) {
handlecentreButtonClick();
}
else {
handleforwardButtonClick();
}
}
try {Thread.sleep(498); }catch (Exception e){}
}
try {Thread.sleep(500);if(isDragging) {isDragging=false;}}catch (Exception e){}
}
}
}).start();
我现在已经完成了我的项目。您可以通过从我的BitBucket Account下载整个项目及其源代码来查看它。