javafx.scene.media.MediaPlayer Java Examples

The following examples show how to use javafx.scene.media.MediaPlayer. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HtmlWebView.java    From Learn-Java-12-Programming with MIT License 9 votes vote down vote up
public void start11(Stage primaryStage) {

        Text txt1 = new Text("What a beautiful music!");
        Text txt2 = new Text("If you don't hear music, turn up the volume.");

        File f = new File("src/main/resources/jb.mp3");
        Media m = new Media(f.toURI().toString());
        MediaPlayer mp = new MediaPlayer(m);
        MediaView mv = new MediaView(mp);

        VBox vb = new VBox(txt1, txt2, mv);
        vb.setSpacing(20);
        vb.setAlignment(Pos.CENTER);
        vb.setPadding(new Insets(10, 10, 10, 10));

        Scene scene = new Scene(vb, 350, 100);

        primaryStage.setScene(scene);
        primaryStage.setTitle("JavaFX with embedded media player");
        primaryStage.onCloseRequestProperty()
                .setValue(e -> System.out.println("Bye! See you later!"));
        primaryStage.show();

        mp.play();
    }
 
Example #2
Source File: Player.java    From gramophy with GNU General Public License v3.0 6 votes vote down vote up
public void pauseResume()
{
    new Thread(new Task<>() {
        @Override
        protected Object call() throws Exception {
            if(mediaPlayer.getStatus().equals(MediaPlayer.Status.PAUSED))
            {
                isPlaying = true;
                dash.musicPanePlayPauseButtonImageView.setImage(dash.pauseIcon);
                mediaPlayer.play();
            }
            else if(mediaPlayer.getStatus().equals(MediaPlayer.Status.PLAYING))
            {
                isPlaying = false;
                dash.musicPanePlayPauseButtonImageView.setImage(dash.playIcon);
                mediaPlayer.pause();
            }
            return null;
        }
    }).start();
}
 
Example #3
Source File: Sound.java    From Cherno with GNU General Public License v3.0 6 votes vote down vote up
private void create(final String file) {
	final File soundFile = new File(file);
	if (!soundFile.exists()) {
		System.err.println("Sound File \"" + file + "\" not found!");
		return;
	}
	String[] strings = file.split("/");
	this.soundFile = strings[strings.length - 1];
	new Thread() {
		public void run() {
			try {
				sound = new MediaPlayer(new Media(soundFile.toURI().toString()));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}.start();
}
 
Example #4
Source File: AudioDemo.java    From phoebus with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void start(final Stage stage)
{
    stage.setTitle("Audio Demo");
    stage.show();

    // Windows and Mac OS X support WAV and MP3
    // Linux: WAV hangs, MP3 results in MediaException for unsupported format
    final File file = new File("../model/src/main/resources/examples/timer/timer.mp3");
    final Media audio = new Media(file.toURI().toString());
    player = new MediaPlayer(audio);
    player.setOnError(() -> System.out.println("Error!"));
    player.setOnStopped(() ->
    {
        System.out.println("Stopped.");
        player.dispose();
        stage.close();
    });
    player.setOnEndOfMedia( () ->
    {
        System.out.println("Done.");
        player.stop();
    });
    // Wasn't necessary with JDK9, but is with 11 on Mac OS X
    player.setStartTime(Duration.seconds(0));
    player.play();
    System.out.println("Playing...");
}
 
Example #5
Source File: PlayerController.java    From Simple-Media-Player with MIT License 6 votes vote down vote up
public void start(String url,boolean popup,int width,int height){
    this.url = url;
    this.popup = popup;

    //MediaView设置
    media = new Media(url);
    mediaPlayer = new MediaPlayer(media);
    mediaView.setMediaPlayer(mediaPlayer);

    //设置播放器,在媒体资源加载完毕后,获取相应的数据,设置组件自适应布局
    setMediaPlayer(width,height);

    //设置各组件动作事件
    setMediaViewOnClick();
    setPlayButton();
    setStopButton();
    setVolumeButton();
    setVolumeSD();
    setProcessSlider();
    setMaximizeButton();

}
 
Example #6
Source File: PlayerController.java    From Simple-Media-Player with MIT License 6 votes vote down vote up
private void setMediaViewOnClick(){
    mediaView.setOnMouseClicked(event -> {
        if(media == null)
            return;
        MediaPlayer.Status status = mediaPlayer.getStatus();
        if(status == MediaPlayer.Status.UNKNOWN || status == MediaPlayer.Status.HALTED ){
            return;
        }
        //当资源处于暂停或停止状态时
        if(status == MediaPlayer.Status.PAUSED || status == MediaPlayer.Status.READY || status == MediaPlayer.Status.STOPPED){
            //当资源播放结束时,重绕资源
            if(atEndOfMedia){
                mediaPlayer.seek(mediaPlayer.getStartTime());
                atEndOfMedia = false;
            }
            mediaPlayer.play();
            setIcon(playBT,pauseIcon,25);
        }else{   //当资源处于播放状态时
            mediaPlayer.pause();
            setIcon(playBT,playIcon,25);
        }
    });
}
 
Example #7
Source File: PlayerController.java    From Simple-Media-Player with MIT License 6 votes vote down vote up
private void setPlayButton(){
    playBT.setOnAction((ActionEvent e)->{
        if(media == null)
            return;
        MediaPlayer.Status status = mediaPlayer.getStatus();
        if(status == MediaPlayer.Status.UNKNOWN || status == MediaPlayer.Status.HALTED ){
            return;
        }
        //当资源处于暂停或停止状态时
        if(status == MediaPlayer.Status.PAUSED || status == MediaPlayer.Status.READY || status == MediaPlayer.Status.STOPPED){
            //当资源播放结束时,重绕资源
            if(atEndOfMedia){
                mediaPlayer.seek(mediaPlayer.getStartTime());
                atEndOfMedia = false;
            }
            mediaPlayer.play();
            setIcon(playBT,pauseIcon,25);
        }else{   //当资源处于播放状态时
            mediaPlayer.pause();
            setIcon(playBT,playIcon,25);
        }
    });
}
 
Example #8
Source File: ChatController.java    From JavaFX-Chat with GNU General Public License v3.0 6 votes vote down vote up
public void newUserNotification(Message msg) {
    Platform.runLater(() -> {
        Image profileImg = new Image(getClass().getClassLoader().getResource("images/" + msg.getPicture().toLowerCase() +".png").toString(),50,50,false,false);
        TrayNotification tray = new TrayNotification();
        tray.setTitle("A new user has joined!");
        tray.setMessage(msg.getName() + " has joined the JavaFX Chatroom!");
        tray.setRectangleFill(Paint.valueOf("#2C3E50"));
        tray.setAnimationType(AnimationType.POPUP);
        tray.setImage(profileImg);
        tray.showAndDismiss(Duration.seconds(5));
        try {
            Media hit = new Media(getClass().getClassLoader().getResource("sounds/notification.wav").toString());
            MediaPlayer mediaPlayer = new MediaPlayer(hit);
            mediaPlayer.play();
        } catch (Exception e) {
            e.printStackTrace();
        }

    });
}
 
Example #9
Source File: EqualizerPresets.java    From Java-MP3-player with MIT License 6 votes vote down vote up
void previous_Mode(int index,JSlider bands[],MediaPlayer mediaPlayer ,JLabel name)
{
	index=(index<0?17:index);
	name.setText(this.name[index]);   

	double previous_val,next_val;
	for(int i=0;i<10;i++)
	{
	    previous_val=mediaPlayer.getAudioEqualizer().getBands().get(i).MAX_GAIN*2;
	    mediaPlayer.getAudioEqualizer().getBands().get(i).setGain(Presets[index][i]);
	    next_val=mediaPlayer.getAudioEqualizer().getBands().get(i).getGain();
	    
	    
	    bands[i].setValue((int)(Math.abs(next_val/previous_val)*100));
	}
		
}
 
Example #10
Source File: AdvancedMedia.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void init(Stage primaryStage) {
    Group root = new Group();
    primaryStage.setScene(new Scene(root));
    mediaPlayer = new MediaPlayer(new Media(MEDIA_URL));
    mediaPlayer.setAutoPlay(true);
    MediaControl mediaControl = new MediaControl(mediaPlayer);
    mediaControl.setMinSize(480,280);
    mediaControl.setPrefSize(480,280);
    mediaControl.setMaxSize(480,280);
    root.getChildren().add(mediaControl);
}
 
Example #11
Source File: WritePaneFrame.java    From oim-fx with MIT License 5 votes vote down vote up
void initMediaPlayer() {
	MediaPlayer mediaPlayer = new MediaPlayer(new Media(MEDIA_URL));
	mediaPlayer.setAutoPlay(true);
	PlayerPane playerPane = new PlayerPane(mediaPlayer);
	
	MediaSimplPane m=new MediaSimplPane();
	m.setUrl(MEDIA_URL);
	m.play();
	box.getChildren().add(playerPane);
	m.setStyle("-fx-background-color:rgba(230, 230, 230, 1)");
	rootPane.setCenter(m);
}
 
Example #12
Source File: JFXRepresentation.java    From phoebus with Eclipse Public License 1.0 5 votes vote down vote up
AudioFuture(final MediaPlayer player)
{
    this.player = player;
    // Player by default just stays in "PLAYING" state
    player.setOnEndOfMedia(() -> player.stop());
    player.play();
    logger.log(Level.INFO, "Playing " + this);
}
 
Example #13
Source File: JFXRepresentation.java    From phoebus with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public String toString()
{
    final MediaPlayer copy = player;
    if (copy == null)
        return "Disposed audio player";
    return "Audio player for " + player.getMedia().getSource() + " (" + player.getStatus() + ")";
}
 
Example #14
Source File: PlayerController.java    From Simple-Media-Player with MIT License 5 votes vote down vote up
public void destroy(){
    if(mediaPlayer.getStatus() == MediaPlayer.Status.PLAYING){
        mediaPlayer.stop();
    }
    mediaPlayer.dispose();   //释放meidaPlayer的Media资源
    media = null;
    mediaPlayer = null;
    System.gc();    //通知JVM垃圾回收器

}
 
Example #15
Source File: MediaPlayerController.java    From AudioBookConverter with GNU General Public License v2.0 5 votes vote down vote up
private void toggleMediaPlayer() {
    MediaPlayer.Status status = mediaPlayer.getStatus();
    if (status == MediaPlayer.Status.HALTED || status == MediaPlayer.Status.UNKNOWN) {
        return;
    }

    if (status == MediaPlayer.Status.READY
            || status == MediaPlayer.Status.PAUSED
            || status == MediaPlayer.Status.STOPPED) {
        mediaPlayer.play();
    } else {
        mediaPlayer.pause();
    }
}
 
Example #16
Source File: VideoView.java    From BotLibre with Eclipse Public License 1.0 5 votes vote down vote up
public void setLoop(boolean loop){
	if(loop){
		mediaPlayer.setCycleCount(MediaPlayer.INDEFINITE);
	}else{
		mediaPlayer.setCycleCount(1);
	}
}
 
Example #17
Source File: VideoView.java    From BotLibre with Eclipse Public License 1.0 5 votes vote down vote up
public void setVideoURI(Uri uri) {
	System.out.println(uri.uri);
	Platform.runLater(new Runnable() {
		@Override
		public void run() {
			Media media = new Media(uri.uri);
			mediaPlayer = new MediaPlayer(media);
			mediaView.setMediaPlayer(mediaPlayer);
			mediaPlayer.setAutoPlay(true);
			mediaPlayer.setCycleCount(MediaPlayer.INDEFINITE);
		}
	});
	
	
}
 
Example #18
Source File: VideoView.java    From BotLibre with Eclipse Public License 1.0 5 votes vote down vote up
public void setLoop(boolean loop){
	if(loop){
		mediaPlayer.setCycleCount(MediaPlayer.INDEFINITE);
	}else{
		mediaPlayer.setCycleCount(1);
	}
}
 
Example #19
Source File: VideoView.java    From BotLibre with Eclipse Public License 1.0 5 votes vote down vote up
public void setVideoURI(Uri uri) {
	System.out.println(uri.uri);
	Platform.runLater(new Runnable() {
		@Override
		public void run() {
			Media media = new Media(uri.uri);
			mediaPlayer = new MediaPlayer(media);
			mediaView.setMediaPlayer(mediaPlayer);
			mediaPlayer.setAutoPlay(true);
			mediaPlayer.setCycleCount(MediaPlayer.INDEFINITE);
		}
	});
	
	
}
 
Example #20
Source File: Exercise_16_21.java    From Intro-to-Java-Programming with MIT License 5 votes vote down vote up
@Override // Override the start method in the Application class
public void start(Stage primaryStage) {
	// Set text field properties
	count.setAlignment(Pos.CENTER);
	count.setFont(Font.font(60));
	count.setPrefColumnCount(4);
	
	// Set meidaplayer to loop
	mediaPlayer.setCycleCount(MediaPlayer.INDEFINITE);

	// Create a pane
	StackPane pane = new StackPane(count);

	// Create animation for stopwatch
	animation = new Timeline(
		new KeyFrame(Duration.millis(1000), e -> run()));
	animation.setCycleCount(Timeline.INDEFINITE);

	count.setOnKeyPressed(e -> {
		if (e.getCode() == KeyCode.ENTER) {
			animation.play();
		}
	});

	// Create a scene and place it in the stage
	Scene scene = new Scene(pane);
	primaryStage.setTitle("Exercise_16_21"); // Set the Stage title
	primaryStage.setScene(scene); // Place the scene in the stage
	primaryStage.show(); // Display the stage
}
 
Example #21
Source File: Exercise_16_26.java    From Intro-to-Java-Programming with MIT License 5 votes vote down vote up
@Override // Override the start method in the Application class
public void start(Stage primaryStage) {
	// Create an image
	ImageView image = new ImageView(new Image(
		"http://cs.armstrong.edu/liang/common/image/flag6.gif"));

	// Create a media player
	MediaPlayer audio = new MediaPlayer(new Media(
		"http://cs.armstrong.edu/liang/common/audio/anthem/anthem6.mp3"));
	audio.play();

	// Create a line
	Line line = new Line(250, 600, 250, -70);

	// Create a pane
	Pane pane = new Pane(image);

	// Create a path transition
	PathTransition pt = new PathTransition();
	pt.setDuration(Duration.millis(70000));
	pt.setPath(line);
	pt.setNode(image);
	pt.setCycleCount(Timeline.INDEFINITE);
	pt.play();

	// Create a scene and place it in the stage
	Scene scene = new Scene(pane, 500, 500);
	primaryStage.setTitle("Exercise_16_26"); // Set the stage title
	primaryStage.setScene(scene); // Place the scene in the stage
	primaryStage.show(); // Display the stage
}
 
Example #22
Source File: Sound.java    From Cherno with GNU General Public License v3.0 5 votes vote down vote up
public void loop() {
	new Thread("Sound: " + soundFile) {
		public void run() {
			sound.stop();
			sound.setCycleCount(MediaPlayer.INDEFINITE);
			sound.play();
		}
	}.start();
}
 
Example #23
Source File: VideoMp4.java    From wandora with GNU General Public License v3.0 5 votes vote down vote up
private MediaPlayer getMediaPlayerFor(Media media) {
    try {
        playerReady = false;
        final MediaPlayer mediaPlayer = new MediaPlayer(media);
        if(mediaPlayer.getError() == null) {
            mediaPlayer.setAutoPlay(false);
            mediaPlayer.currentTimeProperty().addListener(new ChangeListener() {
                @Override
                public void changed(ObservableValue observable, Object oldValue, Object newValue) {
                    Duration newDuration = (Duration) newValue;
                    progressBar.setValue((int) Math.round(newDuration.toSeconds()));
                    updateTimeLabel();
                }
            });
            mediaPlayer.setOnReady(new Runnable() {
                public void run() {
                    playerReady = true;
                    progressBar.setMinimum(0.0);
                    progressBar.setValue(0.0);
                    progressBar.setMaximum(mediaPlayer.getTotalDuration().toSeconds());
                    refreshLayout();
                }
            });
            mediaPlayer.setOnError(new Runnable() {
                public void run() {
                    processError(mediaPlayer.getError());
                }
            });
            return mediaPlayer;
        }
        else {
            processError(mediaPlayer.getError());
        }
    }
    catch(Exception e) {
        processError(e);
    }
    return null;
}
 
Example #24
Source File: PlayerFunctions.java    From aurous-app with GNU General Public License v2.0 5 votes vote down vote up
public static void seek(final int value) {
	final MediaPlayer player = UISession.getMediaPlayer();
	if (player != null) {
		final double d = value / 100D;
		player.seek(Duration.millis(player.getMedia().getDuration()
				.toMillis()
				* d));
	}
}
 
Example #25
Source File: HtmlWebView.java    From Learn-Java-12-Programming with MIT License 5 votes vote down vote up
public void start13(Stage primaryStage) {

        Text txt1 = new Text("What a beautiful movie and sound!");
        Text txt2 = new Text("If you don't hear music, turn up the volume.");

        File fs = new File("src/main/resources/jb.mp3");
        Media ms = new Media(fs.toURI().toString());
        MediaPlayer mps = new MediaPlayer(ms);
        MediaView mvs = new MediaView(mps);

        File fv = new File("src/main/resources/sea.mp4");
        Media mv = new Media(fv.toURI().toString());
        MediaPlayer mpv = new MediaPlayer(mv);
        MediaView mvv = new MediaView(mpv);

        VBox vb = new VBox(txt1, txt2, mvs, mvv);
        vb.setSpacing(20);
        vb.setAlignment(Pos.CENTER);
        vb.setPadding(new Insets(10, 10, 10, 10));

        Scene scene = new Scene(vb, 650, 500);

        primaryStage.setScene(scene);
        primaryStage.setTitle("JavaFX with embedded media player");
        primaryStage.onCloseRequestProperty()
                .setValue(e -> System.out.println("Bye! See you later!"));
        primaryStage.show();

        mpv.play();
        mps.play();
    }
 
Example #26
Source File: Game.java    From CrazyAlpha with GNU General Public License v2.0 5 votes vote down vote up
private Game() {
    backgroundMusic = new MediaPlayer(resouceManager.getMedia("background"));
    backgroundMusic.setVolume(0.5);
    backgroundMusic.setAutoPlay(true);
    backgroundMusic.setCycleCount(MediaPlayer.INDEFINITE);
    buttonOverMusic = new MediaPlayer(resouceManager.getMedia("button_over"));
    buttonClickMusic = new MediaPlayer(resouceManager.getMedia("button_click"));
    hintMusic = new MediaPlayer(resouceManager.getMedia("hint"));
    missMusic = new MediaPlayer(resouceManager.getMedia("error2"));
}
 
Example #27
Source File: MediaTools.java    From MyBox with Apache License 2.0 5 votes vote down vote up
public static MediaPlayer play(String address, double volumn, int cycle) {
    MediaPlayer mp = new MediaPlayer(new Media(address));
    mp.setVolume(volumn);
    mp.setCycleCount(cycle);
    mp.setAutoPlay(true);
    return mp;
}
 
Example #28
Source File: Player.java    From gramophy with GNU General Public License v3.0 5 votes vote down vote up
private void startUpdating()
{
    updaterThread = new Thread(new Task<Void>() {
        @Override
        protected Void call(){
            try
            {
                while(isActive)
                {
                    if(mediaPlayer.getStatus().equals(MediaPlayer.Status.PLAYING))
                    {
                        double currSec = mediaPlayer.getCurrentTime().toSeconds();
                        String currentSimpleTimeStamp = dash.getSecondsToSimpleString(currSec);
                        Platform.runLater(()->dash.nowDurLabel.setText(currentSimpleTimeStamp));

                        double currentProgress = (currSec/totalCurr)*100;
                        if(!dash.songSeek.isValueChanging())
                        {
                            dash.songSeek.setValue(currentProgress);
                            //dash.refreshSlider(dash.songSeek);
                            currentP = currentProgress;
                        }
                    }
                    Thread.sleep(500);
                }
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
            return null;
        }
    });
    updaterThread.start();
}
 
Example #29
Source File: MediaView.java    From DashboardFx with GNU General Public License v3.0 5 votes vote down vote up
@FXML
    private void play(){
            updateValues();
            MediaPlayer.Status status = mediaPlayer.getStatus();
            if (status == MediaPlayer.Status.UNKNOWN
                    || status == MediaPlayer.Status.HALTED)
            {
                // don't do anything in these states
                return;
            }

            if (status == MediaPlayer.Status.PAUSED
                    || status == MediaPlayer.Status.READY
                    || status == MediaPlayer.Status.STOPPED)
            {
                // rewind the movie if we're sitting at the end
                if (atEndOfMedia) {
                    mediaPlayer.seek(mediaPlayer.getStartTime());
                    atEndOfMedia = false;
                    icon.setGlyphName("PLAY");
//                    playButton.setGraphic(imageViewPlay);
                    //playButton.setText(">");
                    updateValues();
                }
                mediaPlayer.play();
                icon.setGlyphName("PAUSE");
//                playButton.setGraphic(imageViewPause);
                //playButton.setText("||");
            }
            else {
                mediaPlayer.pause();
            }
    }
 
Example #30
Source File: HtmlWebView.java    From Learn-Java-12-Programming with MIT License 5 votes vote down vote up
public void start12(Stage primaryStage) {

        Text txt = new Text("What a beautiful movie!");

        File f = new File("src/main/resources/sea.mp4");
        Media m = new Media(f.toURI().toString());
        MediaPlayer mp = new MediaPlayer(m);
        MediaView mv = new MediaView(mp);
        //mv.autosize();
        //mv.preserveRatioProperty();
        //mv.setFitHeight();
        //mv.setFitWidth();
        //mv.fitWidthProperty();
        //mv.fitHeightProperty()

        VBox vb = new VBox(txt, mv);
        vb.setSpacing(20);
        vb.setAlignment(Pos.CENTER);
        vb.setPadding(new Insets(10, 10, 10, 10));

        Scene scene = new Scene(vb, 650, 400);

        primaryStage.setScene(scene);
        primaryStage.setTitle("JavaFX with embedded media player");
        primaryStage.onCloseRequestProperty()
                .setValue(e -> System.out.println("Bye! See you later!"));
        primaryStage.show();

        mp.play();
    }