Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 10

/*

* To change this license header, choose License Headers in Project Properties.


* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/

import java.io.File;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.ResourceBundle;
import java.util.Scanner;
import javafx.application.Platform;
import javafx.beans.InvalidationListener;
import javafx.beans.Observable;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.collections.transformation.SortedList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.control.Slider;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableRow;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.ClipboardContent;
import javafx.scene.input.DataFormat;
import javafx.scene.input.Dragboard;
import javafx.scene.input.MouseEvent;
import javafx.scene.input.TransferMode;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Pane;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.stage.FileChooser;

/**
*
* @author MUHAMMAD ZAIN ALI
*/
public class DJMediaPlayerController implements Initializable {

@FXML
private TextField searchSongTextField;
@FXML
private Label nowPlayingSongLabel;
@FXML
private TableView<SongLibraryTableModel> songLiibraryTableView;
@FXML
private TableColumn<SongLibraryTableModel, String> songTitleCol;
@FXML
private TableColumn<SongLibraryTableModel, String> SongArtistCol;
@FXML
private TableColumn<SongLibraryTableModel, String> SongPlayTimeCol;
@FXML
private TableColumn<SongLibraryTableModel, String> SongFIleNameCol;
@FXML
private Pane playLIstPane;
@FXML
private AnchorPane songLibraryAnchorPane;
@FXML
private TableView<playlistTableViewModel> playlistTableView;
@FXML
private TableColumn<playlistTableViewModel, String> playlistSongTitleCol;
@FXML
private TableColumn<playlistTableViewModel, String> playlistSongRunTimeCol;
@FXML
private Slider playSlider;
@FXML
private Slider volumeSlider;

private static ObservableList<SongLibraryTableModel> songList =


FXCollections.observableArrayList();
private static ObservableList<playlistTableViewModel> playList =
FXCollections.observableArrayList();
private ArrayList<playlistTableViewModel> selections = new ArrayList<>();
private static final DataFormat SERIALIZED_MIME_TYPE = new
DataFormat("application/x-java-serialized-object");

private File Song;


private boolean Deleted;
private boolean newChoice;
private boolean songIsPlaying;
private int index_of_the_song=0;
private Media media;
private MediaPlayer mediaPlayer;
private URI uri;
private boolean isSongPause;
private static String songPath;
/**
* Initializes the controller class.
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
// TODO

reOrderPlayList();
volumeSliderAction();
volumeSlider.setValue(100);
songLiibraryTableView.setOnMouseClicked((MouseEvent event) -> {
if (event.getClickCount() > 1) {
onAddSongToPlaylist();
}
});
// playlistTableView.setOnMouseClicked((MouseEvent event) -> {
// if (event.getClickCount() > 1) {
// playSelectedSong();
// }
// });

}
@FXML
private void SongLibraryBtnAction(ActionEvent event){

songLibraryAnchorPane.setVisible(!songLibraryAnchorPane.isVisible());

@FXML
private void playListBtnAction(ActionEvent event){
playLIstPane.setVisible(!playLIstPane.isVisible());
}

@FXML
private void loadSongLibraryBtnAction(ActionEvent event){
File songFile = getSongFile();
loadFileDataToTableView(songFile);

@FXML
private void playBtnAction(ActionEvent event){
playSongPlaylist();

@FXML
private void pauseBtnAction(ActionEvent event){
isSongPause=true;
songIsPlaying=false;
mediaPlayer.pause();

@FXML
private void stopBtnAction(ActionEvent event){
newChoice=true;
songIsPlaying=false;
mediaPlayer.stop();

@FXML
private void nextBtnAction(ActionEvent event){
songIsPlaying=false;
if(index_of_the_song<playList.size()-1)
index_of_the_song++;
mediaPlayer.stop();
playSongPlaylist();

@FXML
private void previousBtnAction(ActionEvent event){
songIsPlaying=false;
if(index_of_the_song>0)
index_of_the_song--;
mediaPlayer.stop();
playSongPlaylist();

@FXML
private void deletePlayListSongBtnAction(ActionEvent event){
if (playlistTableView.getSelectionModel().getSelectedItem() != null) {
playlistTableViewModel selectedSong =
playlistTableView.getSelectionModel().getSelectedItem();
int index= playlistTableView.getSelectionModel().getSelectedIndex();
playList.remove(index);
}
}

@FXML
private void closeBtnAction(MouseEvent event){
if(mediaPlayer !=null){
mediaPlayer.stop();
}
Platform.exit();
System.exit(0);

private File getSongFile(){


FileChooser fc = new FileChooser();
fc.getExtensionFilters().addAll(new
FileChooser.ExtensionFilter("File","*.txt","*.csv"));
File file = fc.showOpenDialog(null);

songPath = (file.getParentFile().getAbsolutePath())+"\\";
return file;
}

private void searchSongAction(){


FilteredList<SongLibraryTableModel> filteredData = new
FilteredList<>(songList, p -> true);

searchSongTextField.textProperty().addListener((observable, oldValue,
newValue) -> {
filteredData.setPredicate(artist -> {
// If searchSongTextField is empty display all songs
if (newValue == null || newValue.isEmpty()) {
return true;
}
String lowerCaseFilter = newValue.toLowerCase();

if (artist.getSongArtist().toLowerCase().indexOf(lowerCaseFilter) !=
-1) {
return true; // artitst found.
}
return false; // Does not found.
});
});
SortedList<SongLibraryTableModel> sortedData = new
SortedList<>(filteredData);
sortedData.comparatorProperty().bind(songLiibraryTableView.comparatorProperty());
songLiibraryTableView.setItems(sortedData);

private void loadFileDataToTableView(File file){


try {
Scanner in= new Scanner(file);
while (in.hasNext())
{
String data= in.nextLine();
String[] value=data.split("\t");
songList.add(new SongLibraryTableModel(value[0],value[1], value[2],
value[3]));
}
in.close();
}catch(Exception e) {}

songTitleCol.setCellValueFactory(new
PropertyValueFactory<SongLibraryTableModel, String>("songTitle"));
SongArtistCol.setCellValueFactory(new
PropertyValueFactory<SongLibraryTableModel, String>("songArtist"));
SongPlayTimeCol.setCellValueFactory(new
PropertyValueFactory<SongLibraryTableModel, String>("songRunTime"));
SongFIleNameCol.setCellValueFactory(new
PropertyValueFactory<SongLibraryTableModel, String>("songFileName"));
songLiibraryTableView.setItems(null);
songLiibraryTableView.setItems(songList);
searchSongAction();

public void onAddSongToPlaylist() {


if (songLiibraryTableView.getSelectionModel().getSelectedItem() != null) {
SongLibraryTableModel selectedSong =
songLiibraryTableView.getSelectionModel().getSelectedItem();
playList.add(new playlistTableViewModel(selectedSong.getSongTitle(),
selectedSong.getSongRunTime(),selectedSong.getSongFileName()));
playlistSongTitleCol.setCellValueFactory(new
PropertyValueFactory<playlistTableViewModel, String>("songTitle"));
playlistSongRunTimeCol.setCellValueFactory(new
PropertyValueFactory<playlistTableViewModel, String>("songRunTime"));
playlistTableView.setItems(playList);

}
}

private void reOrderPlayList(){


playlistTableView.setRowFactory(tv -> {
TableRow<playlistTableViewModel> row = new TableRow<>();

row.setOnDragDetected(event -> {
if (! row.isEmpty()) {
Integer index = row.getIndex();

selections.clear();//important...
ObservableList<playlistTableViewModel> items =
playlistTableView.getSelectionModel().getSelectedItems();

for(playlistTableViewModel iI:items) {
selections.add(iI);
}

Dragboard db = row.startDragAndDrop(TransferMode.MOVE);
db.setDragView(row.snapshot(null, null));
ClipboardContent cc = new ClipboardContent();
cc.put(SERIALIZED_MIME_TYPE, index);
db.setContent(cc);
event.consume();
}
});

row.setOnDragOver(event -> {
Dragboard db = event.getDragboard();
if (db.hasContent(SERIALIZED_MIME_TYPE)) {
if (row.getIndex() !=
((Integer)db.getContent(SERIALIZED_MIME_TYPE)).intValue()) {
event.acceptTransferModes(TransferMode.COPY_OR_MOVE);
event.consume();
}
}
});

row.setOnDragDropped(event -> {
Dragboard db = event.getDragboard();

if (db.hasContent(SERIALIZED_MIME_TYPE)) {

int dropIndex;
playlistTableViewModel dI=null;

if (row.isEmpty()) {
dropIndex = playlistTableView.getItems().size() ;
} else {
dropIndex = row.getIndex();
dI = playlistTableView.getItems().get(dropIndex);
}
int delta=0;
if(dI!=null)
while(selections.contains(dI)) {
delta=1;
--dropIndex;
if(dropIndex<0) {
dI=null;dropIndex=0;
break;
}
dI = playlistTableView.getItems().get(dropIndex);
}

for(playlistTableViewModel sI:selections) {
playlistTableView.getItems().remove(sI);
}

if(dI!=null)
dropIndex=playlistTableView.getItems().indexOf(dI)+delta;
else if(dropIndex!=0)
dropIndex=playlistTableView.getItems().size();

playlistTableView.getSelectionModel().clearSelection();

for(playlistTableViewModel sI:selections) {
//draggedIndex = selections.get(i);
playlistTableView.getItems().add(dropIndex, sI);
playlistTableView.getSelectionModel().select(dropIndex);
dropIndex++;

event.setDropCompleted(true);
selections.clear();
event.consume();
}
});

return row ;
});

// private void playSelectedSong(){


// if (playlistTableView.getSelectionModel().getSelectedItem() != null) {
// playlistTableViewModel selectedSong =
playlistTableView.getSelectionModel().getSelectedItem();
// index_of_the_song=
playlistTableView.getSelectionModel().getSelectedIndex();
// Song = new File("F:\\Audio\\Punjabi
Songs\\"+playList.get(index_of_the_song).getFileName());
//
nowPlayingSongLabel.setText(playList.get(index_of_the_song).getSongTitle());
// newChoice = true;
// if (Song != null) {
// Deleted = false;
// Play();
// } else {
// mediaPlayer.stop();
// songIsPlaying = false;
// }
//
// }
// }

private void playSongPlaylist(){

if(!playList.isEmpty()){
Song = new File(songPath+playList.get(index_of_the_song).getFileName());

nowPlayingSongLabel.setText(playList.get(index_of_the_song).getSongTitle());
newChoice = true;
if (Song != null) {
Deleted = false;
Play();
mediaPlayer.setVolume(volumeSlider.getValue());
} else {
mediaPlayer.stop();
songIsPlaying = false;
}
}

void Play() {

if (Deleted)
return;
if(songIsPlaying)
return;
if (isSongPause) {
mediaPlayer.play();
mediaPlayer.setVolume(volumeSlider.getValue());
songIsPlaying = true;
isSongPause=false;
return;
}
if (newChoice) {
newChoice = false;

uri = Song.toURI();
uri.toASCIIString();
String path = uri.toString();
media = new Media(path);
mediaPlayer = new MediaPlayer(media);

mediaPlayer.setOnReady(new Runnable() {
public void run() {
mediaPlayer.play();

songIsPlaying = true;
newChoice=false;
playSlider.setMax((int) media.getDuration().toSeconds());
playSlider.setValue(0);

Runnable runnable;
runnable = () -> {
while (mediaPlayer.getCurrentTime().toSeconds() <
media.getDuration().toSeconds()) {
// ===================================
playSlider.setValue((int)
mediaPlayer.getCurrentTime().toSeconds());
// ===================================
}

};
Thread thread = new Thread(runnable);
thread.start();
mediaPlayer.setOnEndOfMedia(new Runnable() {
@Override
public void run() {
mediaPlayer.stop();
thread.stop();
if(index_of_the_song<playList.size()-1){
try {
playList.remove(index_of_the_song);
Thread.sleep(2000); // 1000 milliseconds is one second.
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
Song = new
File(songPath+playList.get(index_of_the_song).getFileName());

nowPlayingSongLabel.setText(playList.get(index_of_the_song).getSongTitle());
playlistTableView.requestFocus();

playlistTableView.getSelectionModel().select(index_of_the_song);
playlistTableView.getFocusModel().focus(index_of_the_song);
newChoice = true;
songIsPlaying=false;
Play();
mediaPlayer.setVolume(volumeSlider.getValue());
}else{
songIsPlaying=false;
playList.remove(index_of_the_song);
index_of_the_song=0;
}

return;
}
});
}
});
}

private void volumeSliderAction(){


Runnable runnable;
runnable = () -> {
volumeSlider.valueProperty().addListener(new InvalidationListener() {
@Override
public void invalidated(Observable observable) {
if (mediaPlayer == null)
{
volumeSlider.setValue(volumeSlider.getValue());
}
else
{
volumeSlider.setValue(volumeSlider.getValue());
mediaPlayer.setVolume((double) (volumeSlider.getValue() /
100.0));
}
}

});
};
Thread volumeThread = new Thread(runnable);
volumeThread.start();
}

You might also like