Sunday, June 26, 2016

77. MediaPlayer

With MediaPlayer, we may stream an audio source.


Since the entire sound is not stored in memory, the MediaPlayer is necessary for large audio files.


package ex77;

import java.net.URL;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.property.SimpleStringProperty;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.stage.Stage;

public class Ex77 extends Application {

    private final String style =
            "-fx-font-family: Georgia; -fx-font-size: 32;"
            +"-fx-text-fill: purple;";

    @Override
    public void start(Stage stage) {

        URL chirpURL = getClass().getResource("/chirp.wav");
        
        Media media = new Media(chirpURL.toString());
        MediaPlayer mediaPlayer = new MediaPlayer(media);
        mediaPlayer.setCycleCount(5);
        
        Button button = new Button("Play");
        button.setStyle(style);
        button.setOnAction(e-> {
            if (button.getText().equals("Play")) {
                mediaPlayer.play();
                button.setText("Exit");
            }
            else Platform.exit();
            
        });
        
        Label label = new Label();
        label.setStyle(style);
        
        label.textProperty().bind(
                new SimpleStringProperty("Current Count: ").
                concat(
                mediaPlayer.currentCountProperty().asString()));
        
        VBox vbox = new VBox(50, button, label);
        vbox.setAlignment(Pos.CENTER);
        vbox.setStyle("-fx-background-color: lime");

        Scene scene = new Scene(vbox, 400, 300);
        stage.setTitle("Example 77. MediaPlayer");

        stage.setScene(scene);
        stage.show();
    }
    
    public static void main(String[] args) {
        launch();
    }
}

This is the output after 2 counts of playing sound. Note the button text has changed form Play to Exit.


No comments:

Post a Comment