lundi 2 février 2015

Why is JavaFX MediaPlayer stuck on status "UNKNOWN"?

I'm trying to create a simple program that makes a certain sound when you type a key on your keyboard. I can't get the sound player to work.


I'm using JavaFX's MediaPlayer object to play .mp3 files, but it's stuck on the UNKNOWN status, and it doesn't play.


It doesn't call any exceptions/errors, and I've run error-handling code on it just in case, but it still doesn't run.


I've also searched around for the solution, but I couldn't find this exact problem with anybody else.


Here's my full code:



// Global Key Listener
import de.ksquared.system.keyboard.*;

import java.io.File;
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.media.*;

public class Main extends Application {

@Override
public void start(Stage primaryStage) throws Exception {

new GlobalKeyListener().addKeyListener(new KeyAdapter() {
@Override public void keyPressed(KeyEvent event) {
int keyCode = event.getVirtualKeyCode();
if(keyCode < 88 && keyCode > 64) {

String file = new File("audio/" + keyCode + ".mp3").toURI().toString();
Media audio = new Media(file);
MediaPlayer mediaPlayer = new MediaPlayer(audio);
mediaPlayer.play();

// This returns "UNKNOWN"
System.out.println(mediaPlayer.getStatus());

// This code never runs, because the audio never plays.
mediaPlayer.setOnReady(new Runnable() {
@Override
public void run() {
System.out.println("PLAYING! YAY!!!");
}
});

}
}
});

while(true)
try { Thread.sleep(100); }
catch(InterruptedException e) { e.printStackTrace(); }

}

}


I know that it is normal that the status begins as UNKNOWN, but it should eventually turn to READY and start playing, calling the event handler and printing out PLAYING! YAY!!!. But it doesn't.


Please explain what I am doing wrong, or if I made some other unrelated simple mistake.


Thanks for any help.


Aucun commentaire:

Enregistrer un commentaire