I am aware that this is possibly a duplicate. I've checked the other questions before and did not succeed in solving my problem. I am trying to build some sort of instant button app with javafx. At some point I play a file with the following code:
if(mediaPlayer != null){
mediaPlayer.stop();
}
File soundFile = new File(Config.getInstantSoundsDirectory() + File.separator + fileName);
Media mediaFile = new Media(soundFile.toURI().toString());
mediaPlayer = new MediaPlayer(mediaFile);
mediaPlayer.setOnEndOfMedia(() -> mediaPlayer.dispose());
mediaPlayer.play();
If I want to delete the file I am using following code:
try {
Files.deleteIfExists(Paths.get(Config.getInstantSoundsDirectory(), fileName));
} catch (IOException e1) {
e1.printStackTrace();
}
It works if I've never played the file before. If I did though, I will get an exception that says I can't delete it because some other process is using it. According to other posts the solution to remove the file handle from the file is to call dispose() on my mediaPlayer, as I am doing right when the file was played. Unfortunately the error persists. Am I maybe missing something ?
Thanks for your help.
Greets Ionic
Edit -> Here is my sample test code:
String filePath = Paths.get(".", "test.mp3").toString();
File soundFile = new File(filePath);
Media hit = new Media(soundFile.toURI().toString());
player = new MediaPlayer(hit);
player.setOnEndOfMedia(() -> {
player.dispose();
try {
Files.deleteIfExists(Paths.get(".", "test.mp3"));
} catch (IOException e) {
e.printStackTrace();
}
});
player.play();