private boolean setAlbumArt( byte[] imageBytes, String mp3Filename, String mp3outputFilename, String username, String title, String detailsUrl) { try { AudioFile f = AudioFileIO.read(new File(mp3Filename)); Tag tag = f.getTagOrCreateAndSetDefault(); tag.setField(FieldKey.ALBUM, username + ": " + title + " via SoundCloud.com"); tag.setField(FieldKey.ARTIST, username); tag.setField(FieldKey.TITLE, title); tag.setField(FieldKey.URL_OFFICIAL_RELEASE_SITE, detailsUrl); Artwork artwork = ArtworkFactory.getNew(); artwork.setBinaryData(imageBytes); artwork.setMimeType("image/jpg"); tag.addField(artwork); f.commit(); return true; } catch (Throwable e) { return false; } }
private void fillMetaInfo() { if (tag == null) { title = audioFile.getFile().getName(); artist = ""; album = ""; album_artist = ""; track = ""; composer = ""; year = ""; diskNumber = ""; genre = ""; } else { title = tag.getFirst(FieldKey.TITLE); if (title.equals("")) { title = audioFile.getFile().getName(); } artist = tag.getFirst(FieldKey.ARTIST); album = tag.getFirst(FieldKey.ALBUM); album_artist = tag.getFirst(FieldKey.ALBUM_ARTIST); track = tag.getFirst(FieldKey.TRACK); composer = tag.getFirst(FieldKey.COMPOSER); year = tag.getFirst(FieldKey.YEAR); diskNumber = tag.getFirst(FieldKey.DISC_NO); genre = tag.getFirst(FieldKey.GENRE); } }
public void testWriteToRelativeMp3File() { File orig = new File("testdata", "testV1.mp3"); if (!orig.isFile()) { System.err.println("Unable to test file - not available"); return; } File testFile = null; Exception exceptionCaught = null; try { testFile = AbstractTestCase.copyAudioToTmp("testV1.mp3"); // Copy up a level coz we need it to be in same folder as working directory so can just // specify filename File outputFile = new File(testFile.getName()); boolean result = copy(testFile, outputFile); assertTrue(result); // make Relative assertTrue(outputFile.exists()); // Read File okay AudioFile af = AudioFileIO.read(outputFile); // Create tag and Change File af.getTagOrCreateAndSetDefault(); af.getTag().setField(ArtworkFactory.createArtworkFromFile(new File("testdata/coverart.jpg"))); af.commit(); } catch (Exception e) { e.printStackTrace(); exceptionCaught = e; } assertNull(exceptionCaught); }
/** * Parse the tmp file for tag data and create associated song * * @param dfi * @return song created from tag data */ public static Song parseFileForSong(DiskFileItem dfi) { // TODO Think about where to move this. File audioFile = new File(dfi.getStoreLocation().toString().replace(".tmp", ".mp3")); // "."+dfi.getContentType().substring(dfi.getContentType().indexOf("/")+1))); if (!dfi.getStoreLocation().renameTo(audioFile)) { log.error( "rename failed - store location:" + dfi.getStoreLocation() + ", audio file:" + audioFile); } AudioFile f = null; try { f = AudioFileIO.read(audioFile); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } Tag tag = f.getTag(); if (tag == null) { tag = f.getTagOrCreateAndSetDefault(); } Song song = new Song(); try { song.setArtist(tag.getFirst(FieldKey.ARTIST)); song.setAlbum(tag.getFirst(FieldKey.ALBUM)); song.setTitle(tag.getFirst(FieldKey.TITLE)); song.setYear(tag.getFirst(FieldKey.YEAR)); song.setTrack(tag.getFirst(FieldKey.TRACK)); song.setFilename(dfi.getName()); } catch (KeyNotFoundException knfe) { log.error("song key not found", knfe); } return song; }
/** * Update the GridFSDBFile in the associated DB with the key/values in updateKeys * * @param updateKeys Map of new tag data * @param file GridFSDBFile to update with tag data * @param db * @param songId ID of Song to update with tag data * @return */ public static boolean updateFile( Map<String, String> updateKeys, GridFSDBFile file, DB db, ObjectId songId) { // TODO updateKeys? File audioFile = null; try { audioFile = File.createTempFile("tmp", ".mp3"); } catch (IOException e) { log.error("tmp file not created", e); } audioFile.deleteOnExit(); AudioFile f = null; ObjectId id = (ObjectId) file.getId(); ObjectId oid = null; try { file.writeTo(audioFile); f = AudioFileIO.read(audioFile); Tag tag = f.getTagOrCreateAndSetDefault(); DBObject q = new BasicDBObject("_id", songId); DBObject o = new BasicDBObject("$set", new BasicDBObject(updateKeys)); if (updateKeys.get("artist") != null) { tag.setField(FieldKey.ARTIST, updateKeys.get("artist")); } if (updateKeys.get("album") != null) { tag.setField(FieldKey.ALBUM, updateKeys.get("album")); } if (updateKeys.get("title") != null) { tag.setField(FieldKey.TITLE, updateKeys.get("title")); } if (updateKeys.get("track") != null) { tag.setField(FieldKey.TRACK, updateKeys.get("track")); } if (updateKeys.get("year") != null) { tag.setField(FieldKey.YEAR, updateKeys.get("year")); } AudioFileIO.write(f); GridFS myFS = new GridFS(db); myFS.remove(id); GridFSInputFile inputFile = putSongFileInDB(f.getFile(), db, file.getContentType(), file.getFilename(), id); oid = (ObjectId) inputFile.getId(); if (oid.equals(id)) { db.getCollection("songs").update(q, o); } } catch (KeyNotFoundException knfe) { log.error("key not found", knfe); } catch (FieldDataInvalidException fdie) { log.error("tried to set field with invalid value", fdie); } catch (Exception e) { log.error("error reading/writing file", e); } return (oid.equals(id)); }
/** * Prechecks before normal write * * <p> * * <ul> * <li>If the tag is actually empty, remove the tag * <li>if the file is not writable, throw exception * <li> * <li>If the file is too small to be a valid file, throw exception * <li> * </ul> * * @param af * @throws CannotWriteException */ private void precheckWrite(AudioFile af) throws CannotWriteException { // Preliminary checks try { if (af.getTag().isEmpty()) { delete(af); return; } } catch (CannotReadException re) { throw new CannotWriteException( ErrorMessage.GENERAL_WRITE_FAILED.getMsg(af.getFile().getPath())); } if (!af.getFile().canWrite()) { logger.severe(ErrorMessage.GENERAL_WRITE_FAILED.getMsg(af.getFile().getPath())); throw new CannotWriteException( ErrorMessage.GENERAL_WRITE_FAILED.getMsg(af.getFile().getPath())); } if (af.getFile().length() <= MINIMUM_FILESIZE) { logger.severe( ErrorMessage.GENERAL_WRITE_FAILED_BECAUSE_FILE_IS_TOO_SMALL.getMsg( af.getFile().getPath())); throw new CannotWriteException( ErrorMessage.GENERAL_WRITE_FAILED_BECAUSE_FILE_IS_TOO_SMALL.getMsg( af.getFile().getPath())); } }
public MetadataHelper(File f, Boolean debug) throws CannotReadException, IOException, TagException, ReadOnlyFileException, InvalidAudioFrameException { audioFile = AudioFileIO.read(f); tag = audioFile.getTag(); audioHeader = audioFile.getAudioHeader(); fillMetaInfo(); fillHeaderInfo(); if (debug) { printResults(); } }
public pfItem( File mp3File, String link, String downloadPath, String description, String category) { if (pubDate == null) pubDate = new Date(); _itemID = itemCount; itemCount++; try { AudioFile f = AudioFileIO.read(mp3File); Tag tag = f.getTag(); _title = tag.getFirst(FieldKey.TITLE); if (_title == null || _title.trim().length() == 0) { _title = mp3File.getName(); } String strTrackNum = tag.getFirst(FieldKey.TRACK); if (strTrackNum == null || strTrackNum.trim().length() == 0) { _trackNumber = _itemID; } else { try { _trackNumber = Integer.parseInt(strTrackNum); } catch (NumberFormatException ex) { _trackNumber = _itemID; } } } catch (CannotReadException ex) { Logger.getLogger(pfItem.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(pfItem.class.getName()).log(Level.SEVERE, null, ex); } catch (TagException ex) { Logger.getLogger(pfItem.class.getName()).log(Level.SEVERE, null, ex); } catch (ReadOnlyFileException ex) { Logger.getLogger(pfItem.class.getName()).log(Level.SEVERE, null, ex); } catch (InvalidAudioFrameException ex) { Logger.getLogger(pfItem.class.getName()).log(Level.SEVERE, null, ex); } _link = link; _description = description; _length = mp3File.length(); _category = category; try { _guid = (downloadPath + URLEncoder.encode(mp3File.getName(), "UTF-8")).replace("+", "%20"); } catch (UnsupportedEncodingException ex) { Logger.getLogger(pfItem.class.getName()).log(Level.SEVERE, null, ex); } }
/** Lets now check the value explicity are what we expect */ public void testTagFieldKeyWrite2() { Exception exceptionCaught = null; try { File testFile = AbstractTestCase.copyAudioToTmp("test1.wma", new File("testwrite1.wma")); AudioFile f = AudioFileIO.read(testFile); AudioFileIO.delete(f); // test fields are written with correct ids f = AudioFileIO.read(testFile); Tag tag = f.getTag(); for (FieldKey key : FieldKey.values()) { if (!(key == FieldKey.COVER_ART)) { tag.addField(tag.createField(key, key.name() + "_value")); } } f.commit(); // Reread File f = AudioFileIO.read(testFile); tag = f.getTag(); TagField tf = tag.getFirstField(AsfFieldKey.ALBUM.getFieldName()); assertEquals("WM/AlbumTitle", tf.getId()); assertEquals("ALBUM_value", ((TagTextField) tf).getContent()); assertEquals("UTF-16LE", ((TagTextField) tf).getEncoding()); tf = tag.getFirstField(AsfFieldKey.ALBUM_ARTIST.getFieldName()); assertEquals("WM/AlbumArtist", tf.getId()); assertEquals("ALBUM_ARTIST_value", ((TagTextField) tf).getContent()); assertEquals("UTF-16LE", ((TagTextField) tf).getEncoding()); tf = tag.getFirstField(AsfFieldKey.AMAZON_ID.getFieldName()); assertEquals("ASIN", tf.getId()); assertEquals("AMAZON_ID_value", ((TagTextField) tf).getContent()); assertEquals("UTF-16LE", ((TagTextField) tf).getEncoding()); tf = tag.getFirstField(AsfFieldKey.TITLE.getFieldName()); assertEquals("TITLE", tf.getId()); assertEquals("TITLE_value", ((TagTextField) tf).getContent()); assertEquals("UTF-16LE", ((TagTextField) tf).getEncoding()); } catch (Exception e) { e.printStackTrace(); exceptionCaught = e; } assertNull(exceptionCaught); }
/** Test reading/writing artwork to Ogg */ public void testReadWriteArtworkFieldsToOggVorbis() { File testFile = null; Exception exceptionCaught = null; try { testFile = AbstractTestCase.copyAudioToTmp("test3.ogg"); // Read File okay AudioFile af = AudioFileIO.read(testFile); Tag tag = af.getTag(); tag.createField(FieldKey.COVER_ART, "test"); } catch (Exception e) { e.printStackTrace(); exceptionCaught = e; } assertNull(exceptionCaught); }
/** * Fetches all the tags from the local music file: - Artist - Album - Title - Genre * * @return Song filled with tags * @throws InvalidAudioFrameException * @throws ReadOnlyFileException * @throws CannotReadException * @throws TagException * @throws IOException */ public Song getSongTags() throws CannotReadException, IOException, TagException, ReadOnlyFileException, InvalidAudioFrameException { // create song Song song = new Song(); // instantiate audio file AudioFile audio = AudioFileIO.read(this.songFile); Tag tag = audio.getTag(); song.setArtist(tag.getFirst(FieldKey.ARTIST)); song.setAlbum(tag.getFirst(FieldKey.ALBUM)); song.setTitle(tag.getFirst(FieldKey.TITLE)); song.setGenre(tag.getFirst(FieldKey.GENRE)); return song; }
/** Test reading/writing artwork to Flac */ public void testReadWriteArtworkFieldsToFlac() { File testFile = null; Exception exceptionCaught = null; try { testFile = AbstractTestCase.copyAudioToTmp("test.flac"); // Read File okay AudioFile af = AudioFileIO.read(testFile); Tag tag = af.getTag(); tag.createField(FieldKey.COVER_ART, "test"); } catch (Exception e) { e.printStackTrace(); exceptionCaught = e; } assertNotNull(exceptionCaught); assertTrue(exceptionCaught instanceof UnsupportedOperationException); }
private void insertMusicMetadata() throws IOException { atts.reset(); System.out.format("Extracting music metadata from %s.\n", src.path()); Tag tags = audio.getTag(); AudioHeader header = audio.getAudioHeader(); insert(FORMAT, header.getFormat()); insert(ENCODINGTYPE, header.getEncodingType()); insert(BITRATE, header.getBitRate()); insert(SAMPLERATE, header.getSampleRate()); insert(LENGTH, header.getTrackLength()); insert(ALBUM, tags.getFirst(FieldKey.ALBUM)); insert(ALBUMARTIST, tags.getFirst(FieldKey.ALBUM_ARTIST)); insert(ARTIST, tags.getFirst(FieldKey.ARTIST)); insert(TITLE, tags.getFirst(FieldKey.TITLE)); insert(TRACKNR, tags.getFirst(FieldKey.TRACK)); insert(DISCNR, tags.getFirst(FieldKey.DISC_NO)); insert(YEAR, tags.getFirst(FieldKey.YEAR)); insert(COMMENT, tags.getFirst(FieldKey.COMMENT)); }
/** * Shouldnt fail just ecause header size doesnt match file size because file plays ok in winamp */ public void testReadFileWithHeaderSizeDoesntMatchFileSize() { File orig = new File("testdata", "test3.wma"); if (!orig.isFile()) { System.err.println("Unable to test file - not available"); return; } Exception exceptionCaught = null; try { File testFile = AbstractTestCase.copyAudioToTmp("test3.wma"); AudioFile f = AudioFileIO.read(testFile); assertEquals("Glass", f.getTag().getFirst(FieldKey.TITLE)); // Now } catch (Exception e) { e.printStackTrace(); exceptionCaught = e; } assertNull(exceptionCaught); }
/** Just create fields for all the tag field keys defined, se if we hit any problems */ public void testTagFieldKeyWrite() { Exception exceptionCaught = null; try { File testFile = AbstractTestCase.copyAudioToTmp("test1.wma", new File("testwrite1.wma")); AudioFile f = AudioFileIO.read(testFile); AudioFileIO.delete(f); // Tests multiple iterations on same file for (int i = 0; i < 2; i++) { f = AudioFileIO.read(testFile); Tag tag = f.getTag(); for (FieldKey key : FieldKey.values()) { if (!(key == FieldKey.COVER_ART)) { tag.setField(tag.createField(key, key.name() + "_value_" + i)); } } f.commit(); f = AudioFileIO.read(testFile); tag = f.getTag(); for (FieldKey key : FieldKey.values()) { /* * Test value retrieval, using multiple access methods. */ if (!(key == FieldKey.COVER_ART)) { String value = key.name() + "_value_" + i; System.out.println("Value is:" + value); assertEquals(value, tag.getFirst(key)); AsfTagTextField atf = (AsfTagTextField) tag.getFields(key).get(0); assertEquals(value, atf.getContent()); atf = (AsfTagTextField) tag.getFields(key).get(0); assertEquals(value, atf.getContent()); } } } } catch (Exception e) { e.printStackTrace(); exceptionCaught = e; } assertNull(exceptionCaught); }
public String getSongTitle(String songFilePath) { String songTitle = "Title"; // Try to get the song title from the ID3 tag. File songFile = new File(songFilePath); AudioFile audioFile = null; Tag tag = null; try { audioFile = AudioFileIO.read(songFile); } catch (CannotReadException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TagException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ReadOnlyFileException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidAudioFrameException e) { // TODO Auto-generated catch block e.printStackTrace(); } tag = audioFile.getTag(); songTitle = tag.getFirst(FieldKey.TITLE); // If the ID3 tag doesn't give us the info we need, just use the file name. if (songTitle.equals("Title") || songTitle.isEmpty()) { int indexOfLastSlash = songTitle.lastIndexOf("/") + 1; int indexOfLastDot = songTitle.lastIndexOf("."); songTitle = songTitle.substring(indexOfLastSlash, indexOfLastDot); } return songTitle; }
/** * writes bpm and key to KEY_START and BPM fields in the tag * * @param filename * @param formattedBpm * @param key */ public boolean updateTags(String filename, String formattedBpm, String key) { File file = new File(filename); try { AudioFile f = AudioFileIO.read(file); if (!setCustomTag(f, "KEY_START", key)) { throw new IOException("Error writing Key Tag"); } if (!c.noBpm) { Tag tag = f.getTag(); if (tag instanceof Mp4Tag) { if (!setCustomTag(f, "BPM", formattedBpm)) { throw new IOException("Error writing BPM Tag"); } } tag.setField(FieldKey.BPM, formattedBpm); } f.commit(); return true; } catch (Exception e) { System.out.println("problem with tags in file " + filename); return false; } }
@Override public BufferedImage getArtwork() { BufferedImage image = super.getArtwork(); if (image == null) { try { AudioFile audioFile = AudioFileIO.read(file); FlacTag tag = (FlacTag) audioFile.getTag(); if (tag != null) { List<MetadataBlockDataPicture> images = tag.getImages(); if (images != null && !images.isEmpty()) { MetadataBlockDataPicture picture = images.get(0); byte[] data = picture.getImageData(); image = imageFromData(data); } } } catch (Throwable e) { LOG.error("Unable to read cover art from flac"); } } return image; }
/** * Create a new MusicFile objecy * * @param musicFile - source music file * @param documentsPath - default documents folder for the user */ public MusicFile(File musicFile, String documentsPath) { // Set the music file and documents path this.musicFile = musicFile; this.documentsPath = documentsPath; // Determine the absolute path for the source music file absolutePath = musicFile.getAbsolutePath(); // Retreive the file extension from the absolute path fileExtension = FilenameUtils.getExtension(absolutePath); // If this is a valid music file, retrieve the Tag, and copy the file to // the destination if (fileExtension.equals("mp3") || fileExtension.equals("m4a") || fileExtension.equals("m4p")) { try { AudioFile audioF = AudioFileIO.read(this.musicFile); musicFileTag = audioF.getTag(); // Set the artist, album, and song titles error = setAttributes(); // Set the destination file if (!error) constructDestination(); } catch (Exception e) { error = true; errorMessage = "unidentified error."; } // Else, this is not a valid music file, set the error flag and // error message } else { errorMessage = "not a valid music file."; error = true; } }
@Override public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException { // System.out.println(file + "\t" + Thread.currentThread()); // addSong(file); final File song = file.toFile(); AudioFile f; Logger.getLogger("org.jaudiotagger").setLevel(Level.OFF); final String extension = getExtension(song.getPath()); if (Arrays.asList(types).contains(extension)) { final String localUrl = "file:///" + AurousStringUtils.htmlEncode(song.getPath().toString().replace("\\", "/")); try { f = AudioFileIO.read(song); final Tag tag = f.getTag(); if (tag != null) { String artist = tag.getFirst(FieldKey.ARTIST); String title = tag.getFirst(FieldKey.TITLE); String album = tag.getFirst(FieldKey.ALBUM); if (StringUtils.isBlank(artist)) { artist = "Unknown"; } if (StringUtils.isBlank(title)) { title = "Unknown"; } if (StringUtils.isBlank(album)) { album = "Unknown"; } final int duration = f.getAudioHeader().getTrackLength(); final String artworkBase64 = "assets/img/noalbumart.png"; if (!DatabaseManager.isInCollection(localUrl)) { DatabaseManager.addSong( title, artist, album, artworkBase64, duration, localUrl, "null", "null"); // System.out.println(localUrl); } } else { final int duration = f.getAudioHeader().getTrackLength(); if (!DatabaseManager.isInCollection(localUrl)) { DatabaseManager.addSong( "Unknown", "Unknown", "Unknown", "assets/img/noalbumart.png", duration, localUrl, "null", "null"); } } } catch (CannotReadException | IOException | TagException | ReadOnlyFileException | InvalidAudioFrameException e) { System.out.println("No headers detected"); // ExceptionWidget widget = new ExceptionWidget(e); // widget.showWidget(); } } return FileVisitResult.CONTINUE; }
private static void setID3(File mp3) { // populate Database with id3 tag information try { // Turn off all logging. This should be moved?? Logger logger = Logger.getLogger("org.jaudiotagger"); logger.setLevel(Level.OFF); File song = mp3; // FileInputStream file = new FileInputStream(song); AudioFile f = AudioFileIO.read(song); Tag tag = f.getTag(); System.out.println("Track Length: " + f.getAudioHeader().getTrackLength()); int bitRate = f.getAudioHeader().getSampleRateAsNumber(); String artist = tag.getFirstArtist(); System.out.println("here " + tag.getFirstArtist()); String album = tag.getFirstAlbum(); String songTitle = tag.getFirstTitle(); InsertValues insert1 = new InsertValues(); insert1.insertInfo(artist, songTitle, bitRate, "Audio_Files"); // System.out.println(tag.getFirstComment()); System.out.println("Year: " + tag.getFirstYear()); // System.out.println(tag.getFirstTrack()); /* * Removed. This is for version 1 only * * int size = (int)song.length(); file.skip(size - 128); byte[] * last128 = new byte[128]; file.read(last128); String id3 = new * String(last128); String tag = id3.substring(0, 3); if * (tag.equals("TAG")) { System.out.println("Title: " + * id3.substring(3, 32)); System.out.println("Artist: " + * id3.substring(33, 62)); System.out.println("Album: " + * id3.substring(63, 91)); System.out.println("Year: " + * id3.substring(93, 97)); } else //System.out.println(mp3 + " does * not contain" + " ID3 info."); */ // file.close(); } catch (Exception e) { System.out.println("file read error error message was e = " + e.toString()); } }
/** * Nimmt die aktuell in <code>tags</code> vorhandenen Metatags, und befŸllt die Editorfelder * dementsprechend, dass diese bearbeitet werden kšnne.<br> * Hierbei ist das bearbeiten eines einzelnen {@link Tag}s als auch das bearbeiten von mehreren * mšglich. * * @see #editTag(Tag) * @see #editTags(ArrayList) */ private void updateEditorControls() { watchComponentsForChange = false; /* Felder zurücksetzen: */ editorChanged = false; ((EditorComboBoxModel) comTitle.getModel()).reset(); ((EditorComboBoxModel) comArtist.getModel()).reset(); ((EditorComboBoxModel) comAlbum.getModel()).reset(); ((EditorComboBoxModel) comGenre.getModel()).reset(); txtTracknumber.setText(""); txtTotalTracks.setText(""); txtDiscnumber.setText(""); txtTotalDiscs.setText(""); txtYear.setText(""); imgArtwork.setArtwork(null); imgArtwork.setChanged(false); if (audioFiles == null || audioFiles.size() == 0) { setEditorEnabled(false); } else { setEditorEnabled(true); if (audioFiles.size() == 1) { // SingleFile-Editing AudioFile audioFile = audioFiles.get(0); Tag tag = audioFile.getTag(); /* Felder aktualisieren: */ comTitle.addItem(tag.getFirstTitle()); comTitle.setSelectedIndex(comTitle.getItemCount() - 1); comArtist.addItem(tag.getFirstArtist()); comArtist.setSelectedIndex(comArtist.getItemCount() - 1); comAlbum.addItem(tag.getFirstAlbum()); comAlbum.setSelectedIndex(comAlbum.getItemCount() - 1); String[] numberBuffer = splitNumberData(tag.getFirstTrack()); txtTracknumber.setText(numberBuffer[0]); txtTracknumber.setEnabled(true); txtTotalTracks.setText(numberBuffer[1]); numberBuffer = splitNumberData(tag.getFirst(TagFieldKey.DISC_NO)); txtDiscnumber.setText(numberBuffer[0]); txtTotalDiscs.setText(numberBuffer[1]); txtYear.setText(tag.getFirstYear()); EditorComboBoxModel model = (EditorComboBoxModel) comGenre.getModel(); String genre = tag.getFirstGenre(); model.addIfNotExists(genre); comGenre.setSelectedItem(genre); try { Artwork artwork = tag.getFirstArtwork(); BufferedImage cover = null; if (artwork != null) cover = ImageIO.read(new ByteArrayInputStream(artwork.getBinaryData())); imgArtwork.setArtwork(cover); imgArtwork.setChanged(false); } catch (Exception e) { e.printStackTrace(); } } else { /* MutliFile-Editing: */ // ComboBoxes befŸllen: // Wenn mehrere Audiodateien gewŠhlt sind, ist es meistens auch der // Fall, dass beispielsweise die verschiedenen Files einen verschiedenen // Album-Tag haben. Damit der User nicht "von null" ein Album eingeben // muss, hat er die Mšglichkeit, zwischen den bereits vorhandenen Varianten // eine auszusuchen. EditorComboBoxModel model = null; String totalTracks = "-1"; String discnumber = "-1"; String totalDiscs = "-1"; for (AudioFile audioFile : audioFiles) { Tag tag = audioFile.getTag(); // Title: model = (EditorComboBoxModel) comTitle.getModel(); model.addIfNotExists(tag.getFirstTitle()); // Artists: model = (EditorComboBoxModel) comArtist.getModel(); model.addIfNotExists(tag.getFirstArtist()); // Albums: model = (EditorComboBoxModel) comAlbum.getModel(); model.addIfNotExists(tag.getFirstAlbum()); // Genre. model = (EditorComboBoxModel) comGenre.getModel(); model.addIfNotExists(tag.getFirstGenre()); // Total Tracks: String[] splitBuffer = splitNumberData(tag.getFirstTrack()); if (totalTracks.equals("-1") || totalTracks.equals(splitBuffer[1])) { totalTracks = splitBuffer[1]; } else { totalTracks = ""; } // Discs: splitBuffer = splitNumberData(tag.getFirst(TagFieldKey.DISC_NO)); if (discnumber.equals("-1") || discnumber.equals(splitBuffer[0])) { discnumber = splitBuffer[0]; } else { discnumber = ""; } // Total Discs: if (totalDiscs.equals("-1") || totalDiscs.equals(splitBuffer[1])) { totalDiscs = splitBuffer[1]; } else { totalDiscs = ""; } } txtTracknumber.setText(""); txtTracknumber.setEnabled(false); txtTotalTracks.setText(totalTracks); txtDiscnumber.setText(discnumber); txtTotalDiscs.setText(totalDiscs); } } watchComponentsForChange = true; }
public void testReadFileWithJpgArtwork() { File orig = new File("testdata", "test6.wma"); if (!orig.isFile()) { System.err.println("Unable to test file - not available"); return; } Exception exceptionCaught = null; try { File testFile = AbstractTestCase.copyAudioToTmp("test6.wma"); AudioFile f = AudioFileIO.read(testFile); Tag tag = f.getTag(); assertEquals(1, tag.getFields(FieldKey.COVER_ART).size()); TagField tagField = tag.getFields(FieldKey.COVER_ART).get(0); assertEquals("WM/Picture", tagField.getId()); assertEquals(5093, tagField.getRawContent().length); // Should have been loaded as special field to make things easier assertTrue(tagField instanceof AsfTagCoverField); AsfTagCoverField coverartField = (AsfTagCoverField) tagField; assertEquals("image/jpeg", coverartField.getMimeType()); assertEquals("coveerart", coverartField.getDescription()); assertEquals(3, coverartField.getPictureType()); assertEquals(200, coverartField.getImage().getWidth()); assertEquals(200, coverartField.getImage().getHeight()); assertEquals(5093, coverartField.getRawContent().length); assertEquals(5046, coverartField.getRawImageData().length); assertEquals(5046, coverartField.getImageDataSize()); assertEquals(coverartField.getRawImageData().length, coverartField.getImageDataSize()); assertEquals(BufferedImage.TYPE_3BYTE_BGR, coverartField.getImage().getType()); /** *** TO SOME MANUAL CHECKING **************** */ // First byte of data is immediatley after the 2 byte Descriptor value assertEquals(0x03, tagField.getRawContent()[0]); // Raw Data consists of Unknown/MimeType/Name and Actual Image, null seperated (two bytes) // Skip first three unknown bytes plus two byte nulls int count = 5; String mimeType = null; String name = null; int endOfMimeType = 0; int endOfName = 0; while (count < tagField.getRawContent().length - 1) { if (tagField.getRawContent()[count] == 0 && tagField.getRawContent()[count + 1] == 0) { if (mimeType == null) { mimeType = new String(tagField.getRawContent(), 5, (count) - 5, "UTF-16LE"); endOfMimeType = count + 2; } else if (name == null) { name = new String( tagField.getRawContent(), endOfMimeType, count - endOfMimeType, "UTF-16LE"); endOfName = count + 2; break; } count += 2; } count += 2; // keep on two byte word boundary } assertEquals("image/jpeg", mimeType); assertEquals("coveerart", name); BufferedImage bi = ImageIO.read( ImageIO.createImageInputStream( new ByteArrayInputStream( tagField.getRawContent(), endOfName, tagField.getRawContent().length - endOfName))); assertNotNull(bi); assertEquals(200, bi.getWidth()); assertEquals(200, bi.getHeight()); assertEquals(BufferedImage.TYPE_3BYTE_BGR, bi.getType()); } catch (Exception e) { e.printStackTrace(); exceptionCaught = e; } assertNull(exceptionCaught); }
// TODO Creates temp file in same folder as the original file, this is safe but would impose a // performance // overhead if the original file is on a networked drive public synchronized void write(AudioFile af) throws CannotWriteException { logger.info("Started writing tag data for file:" + af.getFile().getName()); // Prechecks precheckWrite(af); RandomAccessFile raf = null; RandomAccessFile rafTemp = null; File newFile = null; File result = null; // Create temporary File try { newFile = File.createTempFile( af.getFile().getName().replace('.', '_'), TEMP_FILENAME_SUFFIX, af.getFile().getParentFile()); } // Unable to create temporary file, can happen in Vista if have Create Files/Write Data set to // Deny catch (IOException ioe) { logger.log( Level.SEVERE, ErrorMessage.GENERAL_WRITE_FAILED_TO_CREATE_TEMPORARY_FILE_IN_FOLDER.getMsg( af.getFile().getName(), af.getFile().getParentFile().getAbsolutePath()), ioe); throw new CannotWriteException( ErrorMessage.GENERAL_WRITE_FAILED_TO_CREATE_TEMPORARY_FILE_IN_FOLDER.getMsg( af.getFile().getName(), af.getFile().getParentFile().getAbsolutePath())); } // Open temporary file and actual file for Editing try { rafTemp = new RandomAccessFile(newFile, WRITE_MODE); raf = new RandomAccessFile(af.getFile(), WRITE_MODE); } // Unable to write to writable file, can happen in Vista if have Create Folders/Append Data set // to Deny catch (IOException ioe) { logger.log( Level.SEVERE, ErrorMessage.GENERAL_WRITE_FAILED_TO_OPEN_FILE_FOR_EDITING.getMsg( af.getFile().getAbsolutePath()), ioe); // If we managed to open either file, delete it. try { if (raf != null) { raf.close(); } if (rafTemp != null) { rafTemp.close(); } } catch (IOException ioe2) { // Warn but assume has worked okay logger.log( Level.WARNING, ErrorMessage.GENERAL_WRITE_PROBLEM_CLOSING_FILE_HANDLE.getMsg( af.getFile(), ioe.getMessage()), ioe2); } // Delete the temp file ( we cannot delet until closed correpsonding rafTemp) if (!newFile.delete()) { // Non critical failed deletion logger.warning( ErrorMessage.GENERAL_WRITE_FAILED_TO_DELETE_TEMPORARY_FILE.getMsg( newFile.getAbsolutePath())); } throw new CannotWriteException( ErrorMessage.GENERAL_WRITE_FAILED_TO_OPEN_FILE_FOR_EDITING.getMsg( af.getFile().getAbsolutePath())); } // Write data to File try { raf.seek(0); rafTemp.seek(0); try { if (this.modificationListener != null) { this.modificationListener.fileWillBeModified(af, false); } writeTag(af.getTag(), raf, rafTemp); if (this.modificationListener != null) { this.modificationListener.fileModified(af, newFile); } } catch (ModifyVetoException veto) { throw new CannotWriteException(veto); } } catch (Exception e) { logger.log( Level.SEVERE, ErrorMessage.GENERAL_WRITE_FAILED_BECAUSE.getMsg(af.getFile(), e.getMessage()), e); try { if (raf != null) { raf.close(); } if (rafTemp != null) { rafTemp.close(); } } catch (IOException ioe) { // Warn but assume has worked okay logger.log( Level.WARNING, ErrorMessage.GENERAL_WRITE_PROBLEM_CLOSING_FILE_HANDLE.getMsg( af.getFile().getAbsolutePath(), ioe.getMessage()), ioe); } // Delete the temporary file because either it was never used so lets just tidy up or we did // start writing to it but // the write failed and we havent renamed it back to the original file so we can just delete // it. if (!newFile.delete()) { // Non critical failed deletion logger.warning( ErrorMessage.GENERAL_WRITE_FAILED_TO_DELETE_TEMPORARY_FILE.getMsg( newFile.getAbsolutePath())); } throw new CannotWriteException( ErrorMessage.GENERAL_WRITE_FAILED_BECAUSE.getMsg(af.getFile(), e.getMessage())); } finally { try { if (raf != null) { raf.close(); } if (rafTemp != null) { rafTemp.close(); } } catch (IOException ioe) { // Warn but assume has worked okay logger.log( Level.WARNING, ErrorMessage.GENERAL_WRITE_PROBLEM_CLOSING_FILE_HANDLE.getMsg( af.getFile().getAbsolutePath(), ioe.getMessage()), ioe); } } // Result held in this file result = af.getFile(); // If the temporary file was used if (newFile.length() > 0) { // Rename Original File // Can fail on Vista if have Special Permission 'Delete' set Deny File originalFileBackup = new File( af.getFile().getParentFile().getPath(), AudioFile.getBaseFilename(af.getFile()) + ".old"); boolean renameResult = af.getFile().renameTo(originalFileBackup); if (renameResult == false) { logger.log( Level.SEVERE, ErrorMessage.GENERAL_WRITE_FAILED_TO_RENAME_ORIGINAL_FILE_TO_BACKUP.getMsg( af.getFile().getPath(), originalFileBackup.getName())); throw new CannotWriteException( ErrorMessage.GENERAL_WRITE_FAILED_TO_RENAME_ORIGINAL_FILE_TO_BACKUP.getMsg( af.getFile().getPath(), originalFileBackup.getName())); } // Rename Temp File to Original File renameResult = newFile.renameTo(af.getFile()); if (!renameResult) { // Renamed failed so lets do some checks rename the backup back to the original file // New File doesnt exist if (!newFile.exists()) { logger.warning( ErrorMessage.GENERAL_WRITE_FAILED_NEW_FILE_DOESNT_EXIST.getMsg( newFile.getAbsolutePath())); } // Rename the backup back to the original if (!originalFileBackup.renameTo(af.getFile())) { // TODO now if this happens we are left with testfile.old instead of testfile.mp4 logger.warning( ErrorMessage.GENERAL_WRITE_FAILED_TO_RENAME_ORIGINAL_BACKUP_TO_ORIGINAL.getMsg( originalFileBackup.getAbsolutePath(), af.getFile().getName())); } logger.warning( ErrorMessage.GENERAL_WRITE_FAILED_TO_RENAME_TO_ORIGINAL_FILE.getMsg( af.getFile().getAbsolutePath(), newFile.getName())); throw new CannotWriteException( ErrorMessage.GENERAL_WRITE_FAILED_TO_RENAME_TO_ORIGINAL_FILE.getMsg( af.getFile().getAbsolutePath(), newFile.getName())); } else { // Rename was okay so we can now delete the backup of the original boolean deleteResult = originalFileBackup.delete(); if (!deleteResult) { // Not a disaster but can't delete the backup so make a warning logger.warning( ErrorMessage.GENERAL_WRITE_WARNING_UNABLE_TO_DELETE_BACKUP_FILE.getMsg( originalFileBackup.getAbsolutePath())); } } // Delete the temporary file if still exists if (newFile.exists()) { if (!newFile.delete()) { // Non critical failed deletion logger.warning( ErrorMessage.GENERAL_WRITE_FAILED_TO_DELETE_TEMPORARY_FILE.getMsg(newFile.getPath())); } } } else { // Delete the temporary file that wasn't ever used if (!newFile.delete()) { // Non critical failed deletion logger.warning( ErrorMessage.GENERAL_WRITE_FAILED_TO_DELETE_TEMPORARY_FILE.getMsg(newFile.getPath())); } } if (this.modificationListener != null) { this.modificationListener.fileOperationFinished(result); } }
public void testDeleteFields() throws Exception { // Delete using generic key File testFile = AbstractTestCase.copyAudioToTmp("test1.wma", new File("testDeleteFields.wma")); AudioFile f = AudioFileIO.read(testFile); List<TagField> tagFields = f.getTag().getFields(FieldKey.ALBUM_ARTIST_SORT); assertEquals(0, tagFields.size()); f.getTag().addField(FieldKey.ALBUM_ARTIST_SORT, "artist1"); tagFields = f.getTag().getFields(FieldKey.ALBUM_ARTIST_SORT); assertEquals(1, tagFields.size()); f.getTag().deleteField(FieldKey.ALBUM_ARTIST_SORT); f.commit(); // Delete using flac id f = AudioFileIO.read(testFile); tagFields = f.getTag().getFields(FieldKey.ALBUM_ARTIST_SORT); assertEquals(0, tagFields.size()); f.getTag().addField(FieldKey.ALBUM_ARTIST_SORT, "artist1"); tagFields = f.getTag().getFields(FieldKey.ALBUM_ARTIST_SORT); assertEquals(1, tagFields.size()); f.getTag().deleteField("WM/AlbumArtistSortOrder"); tagFields = f.getTag().getFields(FieldKey.ALBUM_ARTIST_SORT); assertEquals(0, tagFields.size()); f.commit(); f = AudioFileIO.read(testFile); tagFields = f.getTag().getFields(FieldKey.ALBUM_ARTIST_SORT); assertEquals(0, tagFields.size()); }
/** * Delete the tag (if any) present in the given file * * @param af The file to process * @throws CannotWriteException if anything went wrong */ public synchronized void delete(AudioFile af) throws CannotReadException, CannotWriteException { if (!af.getFile().canWrite()) { throw new CannotWriteException( ErrorMessage.GENERAL_DELETE_FAILED.getMsg(af.getFile().getPath())); } if (af.getFile().length() <= MINIMUM_FILESIZE) { throw new CannotWriteException( ErrorMessage.GENERAL_DELETE_FAILED.getMsg(af.getFile().getPath())); } RandomAccessFile raf = null; RandomAccessFile rafTemp = null; File tempF = null; // Will be set to true on VetoException, causing the finally block to discard the tempfile. boolean revert = false; try { tempF = File.createTempFile( af.getFile().getName().replace('.', '_'), TEMP_FILENAME_SUFFIX, af.getFile().getParentFile()); rafTemp = new RandomAccessFile(tempF, WRITE_MODE); raf = new RandomAccessFile(af.getFile(), WRITE_MODE); raf.seek(0); rafTemp.seek(0); try { if (this.modificationListener != null) { this.modificationListener.fileWillBeModified(af, true); } deleteTag(raf, rafTemp); if (this.modificationListener != null) { this.modificationListener.fileModified(af, tempF); } } catch (ModifyVetoException veto) { throw new CannotWriteException(veto); } } catch (Exception e) { revert = true; throw new CannotWriteException("\"" + af.getFile().getAbsolutePath() + "\" :" + e, e); } finally { // will be set to the remaining file. File result = af.getFile(); try { if (raf != null) { raf.close(); } if (rafTemp != null) { rafTemp.close(); } if (tempF.length() > 0 && !revert) { boolean deleteResult = af.getFile().delete(); if (deleteResult == false) { logger.warning( ErrorMessage.GENERAL_WRITE_FAILED_TO_DELETE_ORIGINAL_FILE.getMsg( af.getFile().getPath(), tempF.getPath())); throw new CannotWriteException( ErrorMessage.GENERAL_WRITE_FAILED_TO_DELETE_ORIGINAL_FILE.getMsg( af.getFile().getPath(), tempF.getPath())); } boolean renameResult = tempF.renameTo(af.getFile()); if (renameResult == false) { logger.warning( ErrorMessage.GENERAL_WRITE_FAILED_TO_RENAME_TO_ORIGINAL_FILE.getMsg( af.getFile().getPath(), tempF.getPath())); throw new CannotWriteException( ErrorMessage.GENERAL_WRITE_FAILED_TO_RENAME_TO_ORIGINAL_FILE.getMsg( af.getFile().getPath(), tempF.getPath())); } result = tempF; // If still exists we can now delete if (tempF.exists()) { if (!tempF.delete()) { // Non critical failed deletion logger.warning( ErrorMessage.GENERAL_WRITE_FAILED_TO_DELETE_TEMPORARY_FILE.getMsg( tempF.getPath())); } } } else { // It was created but never used if (!tempF.delete()) { // Non critical failed deletion logger.warning( ErrorMessage.GENERAL_WRITE_FAILED_TO_DELETE_TEMPORARY_FILE.getMsg(tempF.getPath())); } } } catch (Exception ex) { logger.severe( "AudioFileWriter exception cleaning up delete:" + af.getFile().getPath() + " or" + tempF.getAbsolutePath() + ":" + ex); } // Notify listener if (this.modificationListener != null) { this.modificationListener.fileOperationFinished(result); } } }
public static boolean generate_audio_info_xml( File saveLocation, TOTorrent inTorrent, File metaFile) { Map<String, Properties> audio_file_properties = new HashMap<String, Properties>(); if (inTorrent.isSimpleTorrent()) { Properties p = new Properties(); InOrderType type = InOrderType.getType(saveLocation.getName()); if (type != null) { if (type.getFileTypeFilter().equals(FileTypeFilter.Audio)) { try { AudioFile f = AudioFileIO.read(saveLocation); Tag tag = f.getTag(); if (tag != null) { AudioHeader audioHeader = f.getAudioHeader(); setPropsFromTagAndHeader(p, audioHeader, tag); } if (p.size() > 0) { audio_file_properties.put(saveLocation.getName(), p); } } catch (Exception e) { System.err.println("audio tag parse error: " + e.toString()); } } } } else { for (TOTorrentFile torrent_file : inTorrent.getFiles()) { Properties p = new Properties(); audio_file_properties.put(torrent_file.getRelativePath(), p); InOrderType type = InOrderType.getType(torrent_file.getRelativePath()); if (type != null) { if (type.getFileTypeFilter().equals(FileTypeFilter.Audio)) { try { File file = new File(saveLocation, torrent_file.getRelativePath()); AudioFile f = AudioFileIO.read(file); Tag tag = f.getTag(); if (tag != null) { AudioHeader audioHeader = f.getAudioHeader(); setPropsFromTagAndHeader(p, audioHeader, tag); if (p.size() > 0) { audio_file_properties.put(saveLocation.getName(), p); } } } catch (Exception e) { System.err.println("audio tag parse error: " + e.toString()); } } // if it's an audio type } // if this file has a recognizable type } // for over torrent files } if (audio_file_properties.size() > 0) { try { XMLEncoder encoder = new XMLEncoder(new BufferedOutputStream(new FileOutputStream(metaFile))); encoder.writeObject(audio_file_properties); encoder.close(); logger.fine( "wrote audio properties xml for: " + (new String(inTorrent.getName(), "UTF-8"))); } catch (Exception e) { try { logger.warning( "error writing audio properties for: " + new String(inTorrent.getName(), "UTF-8") + " / " + e.toString()); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } e.printStackTrace(); return false; } return true; } return false; }
/** * This will write a custom ID3 tag (TXXX). This works only with MP3 files (Flac with ID3-Tag not * tested). * * @param description The description of the custom tag i.e. "catalognr" There can only be one * custom TXXX tag with that description in one MP3 file * @param text The actual text to be written into the new tag field * @return True if the tag has been properly written, false otherwise */ public static boolean setCustomTag(AudioFile audioFile, String description, String text) throws IOException { FrameBodyTXXX txxxBody = new FrameBodyTXXX(); txxxBody.setDescription(description); txxxBody.setText(text); // Get the tag from the audio file // If there is no ID3Tag create an ID3v2.3 tag Tag tag = audioFile.getTagOrCreateAndSetDefault(); if (tag instanceof AbstractID3Tag) { // If there is only a ID3v1 tag, copy data into new ID3v2.3 tag if (!(tag instanceof ID3v23Tag || tag instanceof ID3v24Tag)) { Tag newTagV23 = null; if (tag instanceof ID3v1Tag) { newTagV23 = new ID3v23Tag((ID3v1Tag) audioFile.getTag()); // Copy old tag data } if (tag instanceof ID3v22Tag) { newTagV23 = new ID3v23Tag((ID3v22Tag) audioFile.getTag()); // Copy old tag data } audioFile.setTag(newTagV23); tag = newTagV23; } AbstractID3v2Frame frame = null; if (tag instanceof ID3v23Tag) { if (((ID3v23Tag) audioFile.getTag()).getInvalidFrames() > 0) { throw new IOException("read some invalid frames!"); } frame = new ID3v23Frame("TXXX"); } else if (tag instanceof ID3v24Tag) { if (((ID3v24Tag) audioFile.getTag()).getInvalidFrames() > 0) { throw new IOException("read some invalid frames!"); } frame = new ID3v24Frame("TXXX"); } frame.setBody(txxxBody); try { tag.setField(frame); } catch (FieldDataInvalidException e) { Logger.getLogger(TrackAnalyzer.class.getName()).log(Level.SEVERE, null, e); return false; } } else if (tag instanceof FlacTag) { try { ((FlacTag) tag).setField(description, text); } catch (KeyNotFoundException ex) { Logger.getLogger(TrackAnalyzer.class.getName()).log(Level.SEVERE, null, ex); return false; } catch (FieldDataInvalidException ex) { return false; } } else if (tag instanceof Mp4Tag) { // TagField field = new Mp4TagTextField("----:com.apple.iTunes:"+description, text); TagField field; field = new Mp4TagReverseDnsField( Mp4TagReverseDnsField.IDENTIFIER + ":" + "com.apple.iTunes" + ":" + description, "com.apple.iTunes", description, text); // TagField field = new Mp4TagTextField(description, text); try { tag.setField(field); } catch (FieldDataInvalidException ex) { Logger.getLogger(TrackAnalyzer.class.getName()).log(Level.SEVERE, null, ex); return false; } } else if (tag instanceof VorbisCommentTag) { try { ((VorbisCommentTag) tag).setField(description, text); } catch (KeyNotFoundException ex) { Logger.getLogger(TrackAnalyzer.class.getName()).log(Level.SEVERE, null, ex); return false; } catch (FieldDataInvalidException ex) { Logger.getLogger(TrackAnalyzer.class.getName()).log(Level.SEVERE, null, ex); return false; } } else { // tag not implented Logger.getLogger(TrackAnalyzer.class.getName()) .log( Level.WARNING, "couldn't write key information for " + audioFile.getFile().getName() + " to tag, because this format is not supported."); return false; } // write changes in tag to file try { audioFile.commit(); } catch (CannotWriteException e) { e.printStackTrace(); return false; } return true; }
public void deleteTag(AudioFile f) throws CannotWriteException { // Because audio file is an instanceof MP3File this directs it to save // taking into account if the tag has been sent to null in which case it will be deleted f.commit(); }
public void writeFile(AudioFile f) throws CannotWriteException { // Because audio file is an instanceof MP3File this directs it to save f.commit(); }