Added album art icons and caching.

This commit is contained in:
neviyn 2016-02-10 19:31:00 +00:00
parent a1515ee9ad
commit 1d860760d6
10 changed files with 211 additions and 75 deletions

View File

@ -11,8 +11,9 @@ import org.jaudiotagger.audio.exceptions.ReadOnlyFileException;
import org.jaudiotagger.tag.Tag; import org.jaudiotagger.tag.Tag;
import org.jaudiotagger.tag.TagException; import org.jaudiotagger.tag.TagException;
import java.io.*; import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.List; import java.util.List;
@ -21,7 +22,7 @@ import java.util.Optional;
public class Application { public class Application {
final String musicFileExtensionRegex = ".*\\.(mp3|mp4|flac)"; static final String musicFileExtensionRegex = ".*\\.(mp3|mp4|flac)";
public Application() { public Application() {
DatabaseManager.init(); DatabaseManager.init();
@ -58,13 +59,14 @@ public class Application {
/** /**
* Walk through all files and directories recursively and index any music files with a correct extension * Walk through all files and directories recursively and index any music files with a correct extension
*
* @param rootDirectory Directory from which to start searching * @param rootDirectory Directory from which to start searching
*/ */
public void processSongs(Path rootDirectory){ public static void processSongs(Path rootDirectory) {
try { try {
Files.walk(rootDirectory) Files.walk(rootDirectory)
.filter(f -> f.toString().matches(musicFileExtensionRegex)) .filter(f -> f.toString().matches(musicFileExtensionRegex))
.map(this::autoParse).filter(Optional::isPresent).map(Optional::get).forEach(Gateway::addSong); .map(Application::autoParse).filter(Optional::isPresent).map(Optional::get).forEach(Gateway::addSong);
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
@ -72,10 +74,11 @@ public class Application {
/** /**
* Extract music metadata from the target file. * Extract music metadata from the target file.
*
* @param targetFile Path to file to extract metadata from. * @param targetFile Path to file to extract metadata from.
* @return Metadata contained in targetFile. * @return Metadata contained in targetFile.
*/ */
public Optional<ExtractedMetadata> autoParse(Path targetFile){ public static Optional<ExtractedMetadata> autoParse(Path targetFile) {
Tag audioTags = null; Tag audioTags = null;
try { try {
audioTags = AudioFileIO.read(targetFile.toFile()).getTag(); audioTags = AudioFileIO.read(targetFile.toFile()).getTag();

View File

@ -0,0 +1,34 @@
package musicplayer;
import musicplayer.model.Album;
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeCellRenderer;
import java.awt.*;
public class LibraryTreeCellRenderer implements TreeCellRenderer {
private JLabel label;
LibraryTreeCellRenderer() {
label = new JLabel();
}
@Override
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
Object o = ((DefaultMutableTreeNode) value).getUserObject();
if (o instanceof Album) {
Album album = (Album) o;
if (album.getAlbumArt().isPresent())
label.setIcon(new ImageIcon(album.getAlbumArt().get()));
else {
label.setIcon(null);
}
} else
label.setIcon(null);
if (o != null)
label.setText(o.toString());
return label;
}
}

View File

@ -11,6 +11,8 @@ import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode; import javax.swing.tree.TreeNode;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.TreeMap;
import java.util.TreeSet;
public class PlayerGUI { public class PlayerGUI {
private JTree libraryView; private JTree libraryView;
@ -29,7 +31,7 @@ public class PlayerGUI {
public PlayerGUI() { public PlayerGUI() {
DatabaseManager.init(); DatabaseManager.init();
populateLibrary(Gateway.listAllSongsGroupedByAlbum().get()); populateLibrary(new TreeMap<>(Gateway.listAllSongsGroupedByAlbum().get()));
} }
private void resetTree() { private void resetTree() {
@ -39,6 +41,7 @@ public class PlayerGUI {
libraryView.setModel(treeModel); libraryView.setModel(treeModel);
libraryView.setRootVisible(false); libraryView.setRootVisible(false);
libraryView.setToggleClickCount(1); libraryView.setToggleClickCount(1);
libraryView.setCellRenderer(new LibraryTreeCellRenderer());
} }
private void populateLibrary(Map<Album, List<Song>> libraryData) { private void populateLibrary(Map<Album, List<Song>> libraryData) {
@ -47,7 +50,7 @@ public class PlayerGUI {
libraryData.forEach((k, v) -> { libraryData.forEach((k, v) -> {
DefaultMutableTreeNode albumNode = new DefaultMutableTreeNode(k); DefaultMutableTreeNode albumNode = new DefaultMutableTreeNode(k);
addNodeToTreeModel(parentNode, albumNode); addNodeToTreeModel(parentNode, albumNode);
v.forEach(x -> addNodeToTreeModel(albumNode, new DefaultMutableTreeNode(x))); new TreeSet<>(v).forEach(x -> addNodeToTreeModel(albumNode, new DefaultMutableTreeNode(x)));
}); });
} }

View File

@ -65,21 +65,38 @@ public class Gateway {
/** /**
* Add a new song to the database. * Add a new song to the database.
*
* @param metadata New song information. * @param metadata New song information.
*/ */
public static void addSong(ExtractedMetadata metadata) { public static void addSong(ExtractedMetadata metadata) {
try (Session session = DatabaseManager.getInstance().getSession()) { try (Session session = DatabaseManager.getInstance().getSession()) {
Optional<Album> albumObj = getOneAlbum(metadata.album);
if(!albumObj.isPresent())
albumObj = Optional.of(new Album(metadata.album));
Optional<Artist> artistObj = getOneArtist(metadata.artist);
if(!artistObj.isPresent())
artistObj = Optional.of(new Artist(metadata.artist));
session.beginTransaction(); session.beginTransaction();
Optional<Album> albumObj = getOneAlbum(metadata.album);
if (!albumObj.isPresent()) {
Album album = new Album(metadata.album);
albumObj = Optional.of(album);
session.save(album);
}
Optional<Artist> artistObj = getOneArtist(metadata.artist);
if (!artistObj.isPresent()) {
Artist artist = new Artist(metadata.artist);
artistObj = Optional.of(artist);
session.save(artist);
}
session.save(new Song(metadata.trackNumber, metadata.title, artistObj.get(), albumObj.get(), metadata.genre, metadata.songFile)); session.save(new Song(metadata.trackNumber, metadata.title, artistObj.get(), albumObj.get(), metadata.genre, metadata.songFile));
session.getTransaction().commit(); session.getTransaction().commit();
} }
} }
public static void updateAllAlbumArt() {
try (Session session = DatabaseManager.getInstance().getSession()) {
@SuppressWarnings("unchecked")
List<Album> albums = session.createCriteria(Album.class).list();
session.beginTransaction();
albums.forEach(Album::refreshAlbumArt);
session.getTransaction().commit();
}
}
} }

View File

@ -1,9 +1,18 @@
package musicplayer.model; package musicplayer.model;
import javax.imageio.ImageIO;
import javax.persistence.*; import javax.persistence.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Optional;
import java.util.Set;
@Entity @Entity
public class Album { public class Album implements Comparable<Album> {
@Id @Id
@GeneratedValue(strategy = GenerationType.AUTO) @GeneratedValue(strategy = GenerationType.AUTO)
@ -11,8 +20,16 @@ public class Album {
private long id; private long id;
@Column(name = "name") @Column(name = "name")
private String name; private String name;
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "album")
private Set<Song> songs;
@Lob
@Column(name = "art", nullable = true, length = 10000)
private byte[] art;
@Transient
private static int imageScaleToSize = 50;
protected Album(){} protected Album() {
}
public Album(String name) { public Album(String name) {
this.name = name; this.name = name;
@ -22,6 +39,33 @@ public class Album {
return name; return name;
} }
public Set<Song> getSongs() {
return songs;
}
public Optional<Image> getAlbumArt() {
if (art == null) return Optional.empty();
try (InputStream in = new ByteArrayInputStream(art)) {
return Optional.of(ImageIO.read(in));
} catch (IOException e) {
return Optional.empty();
}
}
@Transient
public void refreshAlbumArt() {
Optional<BufferedImage> artGet = songs.iterator().next().getAlbumArt();
if (artGet.isPresent()) {
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
ImageIO.write(convertToBufferedImage(artGet.get().getScaledInstance(imageScaleToSize, imageScaleToSize, Image.SCALE_SMOOTH)), "jpg", baos);
baos.flush();
art = baos.toByteArray();
} catch (IOException e) {
art = null;
}
}
}
@SuppressWarnings("MethodWithMultipleReturnPoints") @SuppressWarnings("MethodWithMultipleReturnPoints")
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
@ -41,6 +85,17 @@ public class Album {
return result; return result;
} }
@Transient
public static BufferedImage convertToBufferedImage(Image image) {
BufferedImage newImage = new BufferedImage(
image.getWidth(null), image.getHeight(null),
BufferedImage.TYPE_INT_ARGB);
Graphics2D g = newImage.createGraphics();
g.drawImage(image, 0, 0, null);
g.dispose();
return newImage;
}
public String getName() { public String getName() {
return name; return name;
} }
@ -48,4 +103,9 @@ public class Album {
public long getId() { public long getId() {
return id; return id;
} }
@Override
public int compareTo(Album o) {
return toString().compareToIgnoreCase(o.toString());
}
} }

View File

@ -1,6 +1,7 @@
package musicplayer.model; package musicplayer.model;
import javax.persistence.*; import javax.persistence.*;
import java.util.Set;
@Entity @Entity
public class Artist { public class Artist {
@ -11,8 +12,11 @@ public class Artist {
private long id; private long id;
@Column(name = "name") @Column(name = "name")
private String name; private String name;
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "artist")
private Set<Song> songs;
protected Artist(){} protected Artist() {
}
public Artist(String name) { public Artist(String name) {
this.name = name; this.name = name;
@ -29,6 +33,10 @@ public class Artist {
return name; return name;
} }
public Set<Song> getSongs() {
return songs;
}
@SuppressWarnings("MethodWithMultipleReturnPoints") @SuppressWarnings("MethodWithMultipleReturnPoints")
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {

View File

@ -5,31 +5,35 @@ import javax.persistence.*;
import java.awt.image.BufferedImage; import java.awt.image.BufferedImage;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.NoSuchElementException;
import java.util.Optional; import java.util.Optional;
@Entity @Entity
public class Song { public class Song implements Comparable<Song> {
@Id @Id
@GeneratedValue(strategy = GenerationType.AUTO) @GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id") @Column(name = "id")
private long id; private long id;
@ManyToOne(fetch=FetchType.EAGER,cascade=CascadeType.ALL) @ManyToOne
private Artist artist; private Artist artist;
@Column(name = "genre") @Column(name = "genre")
private String genre; private String genre;
@Column(name = "title") @Column(name = "title")
private String title; private String title;
@ManyToOne(fetch=FetchType.EAGER,cascade=CascadeType.ALL) @ManyToOne
private Album album; private Album album;
@Column(name = "songFile") @Column(name = "songFile")
private String songFile; private String songFile;
@Column(name = "trackNumber") @Column(name = "trackNumber")
private String trackNumber; private String trackNumber;
protected Song(){} protected Song() {
}
public Song(String trackNumber, String title, Artist artist, Album album, String genre, String songFile) { public Song(String trackNumber, String title, Artist artist, Album album, String genre, String songFile) {
this.trackNumber = trackNumber; this.trackNumber = trackNumber;
@ -72,14 +76,14 @@ public class Song {
/** /**
* Try to find album art for this song based on likely image file names in the folder. * Try to find album art for this song based on likely image file names in the folder.
*
* @return BufferedImage of album art or Optional.empty() * @return BufferedImage of album art or Optional.empty()
*/ */
public Optional<BufferedImage> getAlbumArt() { public Optional<BufferedImage> getAlbumArt() {
try { Path dir = Paths.get(songFile).getParent();
Optional<Path> imageFile = Files.walk(getSongFile().getParentFile().toPath()) try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, "*.{jpg,png}")) {
.filter(f -> f.toString().matches("(Folder|Cover).jpg")).findFirst(); return Optional.of(ImageIO.read(stream.iterator().next().toFile()));
return (imageFile.isPresent()) ? Optional.of(ImageIO.read(imageFile.get().toFile())) : Optional.empty(); } catch (IOException | NoSuchElementException ignored) {
} catch (IOException e) {
return Optional.empty(); return Optional.empty();
} }
} }
@ -111,4 +115,11 @@ public class Song {
public String getTrackNumber() { public String getTrackNumber() {
return trackNumber; return trackNumber;
} }
@Override
public int compareTo(Song o) {
if (trackNumber != null && o.getTrackNumber() != null && !trackNumber.isEmpty() && !o.getTrackNumber().isEmpty())
return Integer.parseInt(getTrackNumber()) - Integer.parseInt(o.getTrackNumber());
return (int) (id - o.getId());
}
} }