Java FX - Воспроизведение нового трека с помощью FileChooser Selection - PullRequest
0 голосов
/ 25 февраля 2012

Я создал панель управления / строку меню / медиаплеер, который откроет исходный MP3, но когда я перехожу с одной дорожки на другую, через объект FileChooser он сохраняет тот же MP3 на панели управления.

Если я выполнил mp.stop (), а затем установил новый носитель для mp и запустил mp.play (), он воспроизведет новую дорожку, но не будет управляться должным образом.

Ниже приведены мои два текущих класса:

package gc.mediaplayer;

import java.io.File;
import java.net.MalformedURLException;
import javafx.application.Application;
import javafx.beans.property.ReadOnlyDoubleProperty;
import javafx.beans.value.ChangeListener;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.layout.BorderPane;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javafx.util.Duration;

public class GCMediaPlayer extends Application {

    MediaPlayer tracks;
    MediaControl gcMediaPlayerControl;
    Label mp3Info;
    private ChangeListener<Duration> progressChangeListener;

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("GC-MediaPlayer");

        Group root = new Group();
        Scene scene = new Scene(root, 1024, 768);

        File mp3File = new File("D:\\Selena.mp3");
        String initURL = null;
        try {
            initURL = mp3File.toURL().toExternalForm();
        } catch (MalformedURLException ex) {
            System.out.println("Malformed URL Exception");
        }
        System.out.println(initURL);
        Media initMedia = new Media(initURL);
        tracks = new MediaPlayer(initMedia);
        setMediaControl(tracks);
        System.out.println("Set first track");

        BorderPane border = new BorderPane();
        mp3Info = new Label("TEST");
        MenuBar menuBar = buildMenuBarWithMenus(primaryStage.widthProperty(), scene);

        border.setTop(menuBar);
        border.setCenter(mp3Info);
        border.setBottom(gcMediaPlayerControl);
        System.out.println("Printing Border");

        root.getChildren().add(border);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    private void setMediaControl(MediaPlayer mp3Player)
    {
        System.out.println("Setting Media Viewer");
        gcMediaPlayerControl = new MediaControl(mp3Player);
    }

     private MenuBar buildMenuBarWithMenus(final ReadOnlyDoubleProperty menuWidthProperty, final Scene rootScene)
    {
        final MenuBar menuBar= new MenuBar();

        final Menu menu1 = new Menu("File");

        MenuItem openFile = new MenuItem("Open File");
        openFile.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent e) {
                FileChooser fc = new FileChooser();          
                fc.setInitialDirectory(new File("C:\\"));
                File result = fc.showOpenDialog(rootScene.getWindow());

                if(result != null) 
                {
                    try {
                        String mp3FilePath = result.toURL().toExternalForm();
                        mp3FilePath = mp3FilePath.replaceAll(" ","%20");
                        Media mediaFile = new Media(mp3FilePath);
                        System.out.println("Got New Track");
                        System.out.println("Track DIR: "+mp3FilePath);
                        setNewTrack(mediaFile);
                    } catch (MalformedURLException ex) {
                        System.out.println("Malformed URL Exception");
                    }
                 }
            }
    });
        menu1.getItems().add(openFile);
        menuBar.getMenus().add(menu1);

        final Menu menu2 = new Menu("Options");
        menuBar.getMenus().add(menu2);

        final Menu menu3 = new Menu("Help");
        menuBar.getMenus().add(menu3);

        menuBar.prefWidthProperty().bind(menuWidthProperty);

        return menuBar;
    }

     private void setNewTrack(Media mediaObjFile)
     {
        System.out.println("Stopping Old Media First");
        tracks.stop();
        System.out.println("Setting New Track");
        tracks = new MediaPlayer(mediaObjFile);
        setMediaControl(tracks);
     }
}

Класс MediaControl, который я сейчас использую:

http://docs.oracle.com/javafx/2.0/media/playercontrol.htm

Вы видите что-нибудь, что не мешает? Я, наверное, просто смотрю что-то простое.

Спасибо Матф

1 Ответ

0 голосов
/ 27 февраля 2012

Вы используете Java как C ++.В Java нет ссылок, есть только указатели, поэтому присвоение gcMediaPlayerControl нового значения ничего не изменит на сцене.

Более подробно: следующая строка в вашем коде добавляет медиаплеер в сцену:

border.setBottom(gcMediaPlayerControl);

добавляет один конкретный объект к сцене.

Ваш метод setMediaControl изменяет переменную в классе.Это ничего не меняет в сцене.

private void setMediaControl(MediaPlayer mp3Player)
{
    System.out.println("Setting Media Viewer");
    gcMediaPlayerControl = new MediaControl(mp3Player);
}

Решение:

private void setMediaControl(MediaPlayer mp3Player)
{
    System.out.println("Setting Media Viewer");
    gcMediaPlayerControl = new MediaControl(mp3Player);
    border.setBottom(gcMediaPlayerControl);
}
...