I want to play music in background in my game so I added MediaPlayer
but I have a problem with buffering. When the song is playing in background, every few seconds it stops for a moment. Disk is suddenly spinning faster while the song is stopped so the player probably loads file meanwhile. Is there any way to force player to load whole media before playing? Or is it the problem not related to Java? Other media players play files normally.
Here is the code:
import java.io.File;
import java.util.Arrays;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import javafx.embed.swing.JFXPanel;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
public class GameMusic extends JFXPanel {
public GameMusic(String path){
Make_List(path);
Music();
}
private String[] List = new String[0];
private void Make_List(String dir){
File directory = new File(dir);
File[] fList = directory.listFiles();
for (File file : fList) {
if (file.isFile()) {
if(file.getName().toLowerCase().endsWith(".mp3".toLowerCase()) ) {
List = Arrays.copyOf(List, List.length+1);
List[List.length-1]=file.toURI().toASCIIString();
}
}
else if (file.isDirectory()) {
Make_List(file.getAbsolutePath());
}
}
}
private int x=0;
private MediaPlayer player = null;
private Random rn = new Random();
private boolean next = true;
private void Music() {
TimerTask CheckTime;
CheckTime = new TimerTask() {
@Override
public void run() {
if(next){
next = false;
x=rn.nextInt(List.length);
player = new MediaPlayer(new Media(List[x]));
player.play();
player.setOnReady(new Runnable() {
@Override
public void run() {
String title =(String)player.getMedia().getMetadata().get("title");
String artist = (String)player.getMedia().getMetadata().get("artist");
//those 2 lines are there to just show what song is currently playing
//Start.lt.setTitle("Console playing:"+title+" by "+artist);
//Start.lt.Prntl("Playing:"+title+" by "+artist);
}
});
}
double tt=player.getTotalDuration().toSeconds()-5;
double ct=player.getCurrentTime().toSeconds();
if(tt<=ct)
next =true;
}
};
Timer tmr = new Timer();
tmr.scheduleAtFixedRate(CheckTime, 0, 5000);
}
}
The player should run properly only with this
GameMusic gm = new GameMusic(/* Directory with music files */);
I tried to remove everything that was not required to just play file and it still keeps stopping songs for a moment.
Also when I have written the code like year ago,iIt worked perfectly when files were in internal drive
, now I am using external drive. Can this be a problem?
When I check disc usage it stays at 0%
and every few seconds it jumps up to 70-100%
when player loads file. Song stops mostly when disc usage jumps to 100%
. Is there way to force java to load it faster or load bigger parts? Or is it just the hard drive fault?
I am not native English speaker and it is quite hard for me to explain the problem, so sorry if something is not clear.