diff --git a/pom.xml b/pom.xml
index b2091be..44c18fe 100644
--- a/pom.xml
+++ b/pom.xml
@@ -48,6 +48,12 @@
${junit.version}
test
+
+
+ net.jthink
+ jaudiotagger
+ 3.0.1
+
diff --git a/src/main/java/sbu/javafx/MusicController.java b/src/main/java/sbu/javafx/MusicController.java
index 092ecec..9882bd9 100644
--- a/src/main/java/sbu/javafx/MusicController.java
+++ b/src/main/java/sbu/javafx/MusicController.java
@@ -13,8 +13,15 @@ import javafx.scene.media.MediaPlayer;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.util.Duration;
+import org.jaudiotagger.audio.AudioFile;
+import org.jaudiotagger.audio.AudioFileIO;
+import org.jaudiotagger.audio.AudioHeader;
+import org.jaudiotagger.tag.FieldKey;
+import org.jaudiotagger.tag.Tag;
+import org.jaudiotagger.tag.images.Artwork;
import java.io.File;
+import java.io.FileOutputStream;
import java.util.*;
public class MusicController {
@@ -177,6 +184,61 @@ public class MusicController {
return String.format("%d:%02d", minute, second);
}
+ private Song createSongFromFile(File file){
+ String filePath = file.getAbsolutePath();
+ String title = file.getName();
+ String artist = "Unknown";
+ String album = "Unknown";
+ String coverPath = "";
+ int duration = 0;
+
+ try{
+ AudioFile audioFile = AudioFileIO.read(file);
+ Tag tag = audioFile.getTag();
+ AudioHeader header = audioFile.getAudioHeader();
+
+ if(tag != null){
+ // title
+ String t = tag.getFirst(FieldKey.TITLE);
+ if(t != null && !t.isBlank())
+ title = t;
+
+ // artist
+ String a = tag.getFirst(FieldKey.ARTIST);
+ if(a != null && !a.isBlank())
+ artist = a;
+
+ // album
+ String al = tag.getFirst(FieldKey.ALBUM);
+ if(al != null && !al.isBlank())
+ album = al;
+
+ // cover
+ List artworks = tag.getArtworkList();
+ if(artworks != null && !artworks.isEmpty()){
+ byte[] imageData = artworks.get(0).getBinaryData();
+ File coverFile = new File(
+ System.getProperty("java.io.tmpdir"),
+ title.replaceAll("\\s+", "_") + "_cover.jpg"
+ );
+
+ try(FileOutputStream fos = new FileOutputStream(coverFile)){
+ fos.write(imageData);
+ coverPath = coverFile.getAbsolutePath();
+ }
+ }
+ }
+
+ if(header != null)
+ duration = header.getTrackLength();
+
+ } catch(Exception e){
+ System.out.println("Cannot read metadata, " + e.getMessage());
+ }
+
+ return new Song(title, artist, album, filePath, coverPath, duration);
+ }
+
// ========================================= Control buttons ============================================
@FXML
public void handlePlayPause() {
@@ -238,8 +300,7 @@ public class MusicController {
List files = fileChooser.showOpenMultipleDialog(null);
if(files == null) return;
for(File file : files){
- String name = file.getName();
- Song song = new Song(name, "Unknown", "Unknown", file.getAbsolutePath(), "", 0);
+ Song song = createSongFromFile(file);
library.add(song);
}
libraryCount.setText(library.size() + " Songs");