Search in sources :

Example 6 with AudioFile

use of org.jaudiotagger.audio.AudioFile in project musiccabinet by hakko.

the class AudioTagService method updateMetadata.

public void updateMetadata(File file) {
    String extension = getExtension(file.getFilename()).toUpperCase();
    if (!ALLOWED_EXTENSIONS.contains(extension)) {
        return;
    }
    MetaData metaData = new MetaData();
    metaData.setMediaType(Mediatype.valueOf(extension));
    try {
        AudioFile audioFile = AudioFileIO.read(new java.io.File(file.getDirectory(), file.getFilename()));
        Tag tag = audioFile.getTag();
        if (tag != null) {
            metaData.setArtist(getTagField(tag, ARTIST));
            metaData.setArtistSort(getTagField(tag, ARTIST_SORT));
            metaData.setAlbumArtist(toAlbumArtist(tag));
            metaData.setAlbumArtistSort(getTagField(tag, ALBUM_ARTIST_SORT));
            metaData.setAlbum(toAlbum(getTagField(tag, ALBUM)));
            metaData.setTitle(getTagField(tag, TITLE));
            metaData.setYear(getTagField(tag, YEAR));
            metaData.setGenre(toGenre(getTagField(tag, GENRE)));
            metaData.setLyrics(getTagField(tag, LYRICS));
            metaData.setComposer(getTagField(tag, COMPOSER));
            metaData.setDiscNr(toFirstNumber(getTagField(tag, DISC_NO)));
            metaData.setDiscNrs(toShort(getTagField(tag, DISC_TOTAL)));
            metaData.setTrackNr(toFirstNumber(getTagField(tag, TRACK)));
            metaData.setTrackNrs(toShort(getTagField(tag, TRACK_TOTAL)));
            metaData.setCoverArtEmbedded(tag.getFirstArtwork() != null);
        }
        AudioHeader audioHeader = audioFile.getAudioHeader();
        if (audioHeader != null) {
            metaData.setVbr(audioHeader.isVariableBitRate());
            metaData.setBitrate((short) audioHeader.getBitRateAsNumber());
            metaData.setDuration((short) audioHeader.getTrackLength());
        }
        file.setMetaData(metaData);
    } catch (CannotReadException | IOException | TagException | ReadOnlyFileException | InvalidAudioFrameException | RuntimeException e) {
        // AudioFileIO has been seen to throw NumberFormatException
        LOG.warn("Could not read metadata of file " + file.getFilename() + " from " + file.getDirectory(), e);
    }
}
Also used : AudioHeader(org.jaudiotagger.audio.AudioHeader) CannotReadException(org.jaudiotagger.audio.exceptions.CannotReadException) InvalidAudioFrameException(org.jaudiotagger.audio.exceptions.InvalidAudioFrameException) IOException(java.io.IOException) AudioFile(org.jaudiotagger.audio.AudioFile) TagException(org.jaudiotagger.tag.TagException) MetaData(com.github.hakko.musiccabinet.domain.model.library.MetaData) ReadOnlyFileException(org.jaudiotagger.audio.exceptions.ReadOnlyFileException) FlacTag(org.jaudiotagger.tag.flac.FlacTag) Tag(org.jaudiotagger.tag.Tag) AbstractID3v2Tag(org.jaudiotagger.tag.id3.AbstractID3v2Tag)

Example 7 with AudioFile

use of org.jaudiotagger.audio.AudioFile in project musiccabinet by hakko.

the class AudioTagService method getArtwork.

public Artwork getArtwork(java.io.File file) throws ApplicationException {
    Tag tag = null;
    try {
        AudioFile audioFile = AudioFileIO.read(file);
        tag = audioFile.getTag();
    } catch (CannotReadException | IOException | TagException | ReadOnlyFileException | InvalidAudioFrameException | RuntimeException e) {
        throw new ApplicationException("Failed reading artwork from file " + file, e);
    }
    return tag == null ? null : tag.getFirstArtwork();
}
Also used : AudioFile(org.jaudiotagger.audio.AudioFile) ApplicationException(com.github.hakko.musiccabinet.exception.ApplicationException) CannotReadException(org.jaudiotagger.audio.exceptions.CannotReadException) TagException(org.jaudiotagger.tag.TagException) InvalidAudioFrameException(org.jaudiotagger.audio.exceptions.InvalidAudioFrameException) ReadOnlyFileException(org.jaudiotagger.audio.exceptions.ReadOnlyFileException) FlacTag(org.jaudiotagger.tag.flac.FlacTag) Tag(org.jaudiotagger.tag.Tag) AbstractID3v2Tag(org.jaudiotagger.tag.id3.AbstractID3v2Tag) IOException(java.io.IOException)

Example 8 with AudioFile

use of org.jaudiotagger.audio.AudioFile in project MusicDNA by harjot-oberai.

the class AudioFileWriter method write.

/**
     * Write the tag (if not empty) present in the AudioFile in the associated
     * File
     *
     * @param af The file we want to process
     * @throws CannotWriteException if anything went wrong
     */
// 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 void write(AudioFile af) throws CannotWriteException {
    logger.config("Started writing tag data for file:" + af.getFile().getName());
    // Prechecks
    precheckWrite(af);
    //mp3's use a different mechanism to the other formats
    if (af instanceof MP3File) {
        af.commit();
        return;
    }
    RandomAccessFile raf = null;
    RandomAccessFile rafTemp = null;
    File newFile;
    File result;
    // Create temporary File
    try {
        newFile = File.createTempFile(af.getFile().getName().replace('.', '_'), TEMP_FILENAME_SUFFIX, af.getFile().getParentFile());
    }// Files/Write Data set to Deny
     catch (IOException ioe) {
        if (ioe.getMessage().equals(FILE_NAME_TOO_LONG) && (af.getFile().getName().length() > FILE_NAME_TOO_LONG_SAFE_LIMIT)) {
            try {
                newFile = File.createTempFile(af.getFile().getName().substring(0, FILE_NAME_TOO_LONG_SAFE_LIMIT).replace('.', '_'), TEMP_FILENAME_SUFFIX, af.getFile().getParentFile());
            } catch (IOException ioe2) {
                logger.log(Level.SEVERE, ErrorMessage.GENERAL_WRITE_FAILED_TO_CREATE_TEMPORARY_FILE_IN_FOLDER.getMsg(af.getFile().getName(), af.getFile().getParentFile().getAbsolutePath()), ioe2);
                throw new CannotWriteException(ErrorMessage.GENERAL_WRITE_FAILED_TO_CREATE_TEMPORARY_FILE_IN_FOLDER.getMsg(af.getFile().getName(), af.getFile().getParentFile().getAbsolutePath()));
            }
        } else {
            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);
    }// 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);
        }
        // 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);
        }
        // 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().getAbsoluteFile().getParentFile().getPath(), AudioFile.getBaseFilename(af.getFile()) + ".old");
        //If already exists modify the suffix
        int count = 1;
        while (originalFileBackup.exists()) {
            originalFileBackup = new File(af.getFile().getAbsoluteFile().getParentFile().getPath(), AudioFile.getBaseFilename(af.getFile()) + ".old" + count);
            count++;
        }
        boolean renameResult = Utils.rename(af.getFile(), originalFileBackup);
        if (!renameResult) {
            logger.log(Level.SEVERE, ErrorMessage.GENERAL_WRITE_FAILED_TO_RENAME_ORIGINAL_FILE_TO_BACKUP.getMsg(af.getFile().getAbsolutePath(), originalFileBackup.getName()));
            //Delete the temp file because write has failed
            if (newFile != null) {
                newFile.delete();
            }
            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 = Utils.rename(newFile, af.getFile());
        if (!renameResult) {
            // 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'timer 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'timer 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);
    }
}
Also used : CannotWriteException(org.jaudiotagger.audio.exceptions.CannotWriteException) RandomAccessFile(java.io.RandomAccessFile) IOException(java.io.IOException) RandomAccessFile(java.io.RandomAccessFile) AudioFile(org.jaudiotagger.audio.AudioFile) File(java.io.File) MP3File(org.jaudiotagger.audio.mp3.MP3File) ModifyVetoException(org.jaudiotagger.audio.exceptions.ModifyVetoException) CannotReadException(org.jaudiotagger.audio.exceptions.CannotReadException) ModifyVetoException(org.jaudiotagger.audio.exceptions.ModifyVetoException) IOException(java.io.IOException) CannotWriteException(org.jaudiotagger.audio.exceptions.CannotWriteException) MP3File(org.jaudiotagger.audio.mp3.MP3File)

Example 9 with AudioFile

use of org.jaudiotagger.audio.AudioFile in project MusicDNA by harjot-oberai.

the class AsfFileReader method read.

/**
     * {@inheritDoc}
     */
@Override
public AudioFile read(final File f) throws CannotReadException, IOException, TagException, ReadOnlyFileException, InvalidAudioFrameException {
    if (!f.canRead()) {
        throw new CannotReadException(ErrorMessage.GENERAL_READ_FAILED_DO_NOT_HAVE_PERMISSION_TO_READ_FILE.getMsg(f.getAbsolutePath()));
    }
    InputStream stream = null;
    try {
        stream = new FullRequestInputStream(new BufferedInputStream(new FileInputStream(f)));
        final AsfHeader header = HEADER_READER.read(Utils.readGUID(stream), stream, 0);
        if (header == null) {
            throw new CannotReadException(ErrorMessage.ASF_HEADER_MISSING.getMsg(f.getAbsolutePath()));
        }
        if (header.getFileHeader() == null) {
            throw new CannotReadException(ErrorMessage.ASF_FILE_HEADER_MISSING.getMsg(f.getAbsolutePath()));
        }
        // Just log a warning because file seems to play okay
        if (header.getFileHeader().getFileSize().longValue() != f.length()) {
            logger.warning(ErrorMessage.ASF_FILE_HEADER_SIZE_DOES_NOT_MATCH_FILE_SIZE.getMsg(f.getAbsolutePath(), header.getFileHeader().getFileSize().longValue(), f.length()));
        }
        return new AudioFile(f, getAudioHeader(header), getTag(header));
    } catch (final CannotReadException e) {
        throw e;
    } catch (final Exception e) {
        throw new CannotReadException("\"" + f + "\" :" + e, e);
    } finally {
        try {
            if (stream != null) {
                stream.close();
            }
        } catch (final Exception ex) {
            LOGGER.severe("\"" + f + "\" :" + ex);
        }
    }
}
Also used : AudioFile(org.jaudiotagger.audio.AudioFile) CannotReadException(org.jaudiotagger.audio.exceptions.CannotReadException) AsfHeader(org.jaudiotagger.audio.asf.data.AsfHeader) ReadOnlyFileException(org.jaudiotagger.audio.exceptions.ReadOnlyFileException) CannotReadException(org.jaudiotagger.audio.exceptions.CannotReadException) TagException(org.jaudiotagger.tag.TagException) InvalidAudioFrameException(org.jaudiotagger.audio.exceptions.InvalidAudioFrameException)

Example 10 with AudioFile

use of org.jaudiotagger.audio.AudioFile in project libresonic by Libresonic.

the class JaudiotaggerParser method getArtwork.

private Artwork getArtwork(MediaFile file) throws Exception {
    AudioFile audioFile = AudioFileIO.read(file.getFile());
    Tag tag = audioFile.getTag();
    return tag == null ? null : tag.getFirstArtwork();
}
Also used : AudioFile(org.jaudiotagger.audio.AudioFile) Tag(org.jaudiotagger.tag.Tag)

Aggregations

AudioFile (org.jaudiotagger.audio.AudioFile)23 IOException (java.io.IOException)17 CannotReadException (org.jaudiotagger.audio.exceptions.CannotReadException)17 Tag (org.jaudiotagger.tag.Tag)17 File (java.io.File)16 InvalidAudioFrameException (org.jaudiotagger.audio.exceptions.InvalidAudioFrameException)15 ReadOnlyFileException (org.jaudiotagger.audio.exceptions.ReadOnlyFileException)15 TagException (org.jaudiotagger.tag.TagException)14 CannotWriteException (org.jaudiotagger.audio.exceptions.CannotWriteException)11 Cursor (android.database.Cursor)6 FieldDataInvalidException (org.jaudiotagger.tag.FieldDataInvalidException)5 KeyNotFoundException (org.jaudiotagger.tag.KeyNotFoundException)5 FileOutputStream (java.io.FileOutputStream)4 ContentValues (android.content.ContentValues)3 Paint (android.graphics.Paint)3 RandomAccessFile (java.io.RandomAccessFile)3 NoSuchElementException (java.util.NoSuchElementException)3 Intent (android.content.Intent)2 DocumentFile (android.support.v4.provider.DocumentFile)2 DBAccessHelper (com.jams.music.player.DBHelpers.DBAccessHelper)2