2017-04-26 2 views
0

나는 튜토리얼을 따라 왔으며 비슷한 스레드를 여기에서 읽었지만 FXML을 사용할 때 똑같은 것을 표현하기 위해 애 쓰고있다.MP3 시간 경과.

본질적으로 나는 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

레이블 텍스트를 미디어 플레이어의 [현재 시간 속성] (http://docs.oracle.com/javase/8/javafx/api/javafx/scene/media/MediaPlayer.html#currentTimeProperty)에 바인딩하기 만하면됩니다. –

+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입니다.