Search in sources :

Example 11 with AudioFile

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

the class JaudiotaggerParser method getRawMetaData.

/**
     * Parses meta data for the given music file. No guessing or reformatting is done.
     *
     *
     * @param file The music file to parse.
     * @return Meta data for the file.
     */
@Override
public MetaData getRawMetaData(File file) {
    MetaData metaData = new MetaData();
    try {
        AudioFile audioFile = AudioFileIO.read(file);
        Tag tag = audioFile.getTag();
        if (tag != null) {
            metaData.setAlbumName(getTagField(tag, FieldKey.ALBUM));
            metaData.setTitle(getTagField(tag, FieldKey.TITLE));
            metaData.setYear(parseYear(getTagField(tag, FieldKey.YEAR)));
            metaData.setGenre(mapGenre(getTagField(tag, FieldKey.GENRE)));
            metaData.setDiscNumber(parseInteger(getTagField(tag, FieldKey.DISC_NO)));
            metaData.setTrackNumber(parseTrackNumber(getTagField(tag, FieldKey.TRACK)));
            String songArtist = getTagField(tag, FieldKey.ARTIST);
            String albumArtist = getTagField(tag, FieldKey.ALBUM_ARTIST);
            metaData.setArtist(StringUtils.isBlank(songArtist) ? albumArtist : songArtist);
            metaData.setAlbumArtist(StringUtils.isBlank(albumArtist) ? songArtist : albumArtist);
        }
        AudioHeader audioHeader = audioFile.getAudioHeader();
        if (audioHeader != null) {
            metaData.setVariableBitRate(audioHeader.isVariableBitRate());
            metaData.setBitRate((int) audioHeader.getBitRateAsNumber());
            metaData.setDurationSeconds(audioHeader.getTrackLength());
        }
    } catch (Throwable x) {
        LOG.warn("Error when parsing tags in " + file, x);
    }
    return metaData;
}
Also used : AudioFile(org.jaudiotagger.audio.AudioFile) AudioHeader(org.jaudiotagger.audio.AudioHeader) Tag(org.jaudiotagger.tag.Tag)

Example 12 with AudioFile

use of org.jaudiotagger.audio.AudioFile in project Shuttle by timusus.

the class ShuttleApplication method repairMediaStoreYearFromTags.

@NonNull
private Completable repairMediaStoreYearFromTags() {
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        return Completable.complete();
    }
    return DataManager.getInstance().getSongsObservable(value -> value.year < 1).first(Collections.emptyList()).map(songs -> Stream.of(songs).flatMap(song -> {
        if (!TextUtils.isEmpty(song.path)) {
            File file = new File(song.path);
            if (file.exists()) {
                try {
                    AudioFile audioFile = AudioFileIO.read(file);
                    Tag tag = audioFile.getTag();
                    if (tag != null) {
                        String year = tag.getFirst(FieldKey.YEAR);
                        int yearInt = StringUtils.parseInt(year);
                        if (yearInt > 0) {
                            song.year = yearInt;
                            ContentValues contentValues = new ContentValues();
                            contentValues.put(MediaStore.Audio.Media.YEAR, yearInt);
                            return Stream.of(ContentProviderOperation.newUpdate(ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, song.id)).withValues(contentValues).build());
                        }
                    }
                } catch (CannotReadException | IOException | TagException | ReadOnlyFileException | InvalidAudioFrameException e) {
                    e.printStackTrace();
                }
            }
        }
        return Stream.empty();
    }).collect(Collectors.toCollection(ArrayList::new))).doOnSuccess(contentProviderOperations -> getContentResolver().applyBatch(MediaStore.AUTHORITY, contentProviderOperations)).flatMapCompletable(songs -> Completable.complete());
}
Also used : ContentValues(android.content.ContentValues) ContentProviderOperation(android.content.ContentProviderOperation) Genre(com.simplecity.amp_library.model.Genre) PackageManager(android.content.pm.PackageManager) CrashlyticsCore(com.crashlytics.android.core.CrashlyticsCore) Completable(io.reactivex.Completable) PlayCountTable(com.simplecity.amp_library.sql.providers.PlayCountTable) CastConfiguration(com.google.android.libraries.cast.companionlibrary.cast.CastConfiguration) AnalyticsManager(com.simplecity.amp_library.utils.AnalyticsManager) UserSelectedArtwork(com.simplecity.amp_library.model.UserSelectedArtwork) Manifest(android.Manifest) DaggerAppComponent(com.simplecity.amp_library.dagger.component.DaggerAppComponent) AudioFile(org.jaudiotagger.audio.AudioFile) MediaStore(android.provider.MediaStore) Schedulers(io.reactivex.schedulers.Schedulers) Log(android.util.Log) FirebaseAnalytics(com.google.firebase.analytics.FirebaseAnalytics) FieldKey(org.jaudiotagger.tag.FieldKey) LogUtils(com.simplecity.amp_library.utils.LogUtils) ContextCompat(android.support.v4.content.ContextCompat) VideoCastManager(com.google.android.libraries.cast.companionlibrary.cast.VideoCastManager) Logger(java.util.logging.Logger) SettingsManager(com.simplecity.amp_library.utils.SettingsManager) PreferenceManager(android.support.v7.preference.PreferenceManager) Query(com.simplecity.amp_library.model.Query) List(java.util.List) Config(com.simplecity.amp_library.constants.Config) Application(android.app.Application) TagException(org.jaudiotagger.tag.TagException) AudioFileIO(org.jaudiotagger.audio.AudioFileIO) Fabric(io.fabric.sdk.android.Fabric) CompletableTransformer(io.reactivex.CompletableTransformer) InvalidAudioFrameException(org.jaudiotagger.audio.exceptions.InvalidAudioFrameException) ContentValues(android.content.ContentValues) Answers(com.crashlytics.android.answers.Answers) SqlUtils(com.simplecity.amp_library.sql.SqlUtils) AppModule(com.simplecity.amp_library.dagger.module.AppModule) ReadOnlyFileException(org.jaudiotagger.audio.exceptions.ReadOnlyFileException) CannotReadException(org.jaudiotagger.audio.exceptions.CannotReadException) TagOptionSingleton(org.jaudiotagger.tag.TagOptionSingleton) Stream(com.annimon.stream.Stream) Environment(android.os.Environment) RefWatcher(com.squareup.leakcanary.RefWatcher) HashMap(java.util.HashMap) NonNull(android.support.annotation.NonNull) StringUtils(com.simplecity.amp_library.utils.StringUtils) InputMethodManagerLeaks(com.simplecity.amp_library.utils.InputMethodManagerLeaks) ArrayList(java.util.ArrayList) Level(java.util.logging.Level) Observable(io.reactivex.Observable) AppComponent(com.simplecity.amp_library.dagger.component.AppComponent) SqlBriteUtils(com.simplecity.amp_library.sql.sqlbrite.SqlBriteUtils) Collectors(com.annimon.stream.Collectors) TextUtils(android.text.TextUtils) IOException(java.io.IOException) Tag(org.jaudiotagger.tag.Tag) CustomArtworkTable(com.simplecity.amp_library.sql.databases.CustomArtworkTable) File(java.io.File) TimeUnit(java.util.concurrent.TimeUnit) Glide(com.bumptech.glide.Glide) SharedPreferences(android.content.SharedPreferences) StrictMode(android.os.StrictMode) Crashlytics(com.crashlytics.android.Crashlytics) DataManager(com.simplecity.amp_library.utils.DataManager) LeakCanary(com.squareup.leakcanary.LeakCanary) LegacyUtils(com.simplecity.amp_library.utils.LegacyUtils) Collections(java.util.Collections) ContentUris(android.content.ContentUris) FirebaseApp(com.google.firebase.FirebaseApp) CannotReadException(org.jaudiotagger.audio.exceptions.CannotReadException) InvalidAudioFrameException(org.jaudiotagger.audio.exceptions.InvalidAudioFrameException) ArrayList(java.util.ArrayList) IOException(java.io.IOException) AudioFile(org.jaudiotagger.audio.AudioFile) TagException(org.jaudiotagger.tag.TagException) ReadOnlyFileException(org.jaudiotagger.audio.exceptions.ReadOnlyFileException) Tag(org.jaudiotagger.tag.Tag) AudioFile(org.jaudiotagger.audio.AudioFile) File(java.io.File) NonNull(android.support.annotation.NonNull)

Example 13 with AudioFile

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

the class AudioFileReader method read.

/*
      * Reads the given file, and return an AudioFile object containing the Tag
      * and the encoding infos present in the file. If the file has no tag, an
      * empty one is returned. If the encodinginfo is not valid , an exception is thrown.
      *
      * @param f The file to read
      * @exception CannotReadException If anything went bad during the read of this file
      */
public AudioFile read(File f) throws CannotReadException, IOException, TagException, ReadOnlyFileException, InvalidAudioFrameException {
    if (logger.isLoggable(Level.CONFIG)) {
        logger.config(ErrorMessage.GENERAL_READ.getMsg(f.getAbsolutePath()));
    }
    if (!f.canRead()) {
        throw new CannotReadException(ErrorMessage.GENERAL_READ_FAILED_FILE_TOO_SMALL.getMsg(f.getAbsolutePath()));
    }
    if (f.length() <= MINIMUM_SIZE_FOR_VALID_AUDIO_FILE) {
        throw new CannotReadException(ErrorMessage.GENERAL_READ_FAILED_FILE_TOO_SMALL.getMsg(f.getAbsolutePath()));
    }
    RandomAccessFile raf = null;
    try {
        raf = new RandomAccessFile(f, "r");
        raf.seek(0);
        GenericAudioHeader info = getEncodingInfo(raf);
        raf.seek(0);
        Tag tag = getTag(raf);
        return new AudioFile(f, info, tag);
    } catch (CannotReadException cre) {
        throw cre;
    } catch (Exception e) {
        logger.log(Level.SEVERE, ErrorMessage.GENERAL_READ.getMsg(f.getAbsolutePath()), e);
        throw new CannotReadException(f.getAbsolutePath() + ":" + e.getMessage(), e);
    } finally {
        try {
            if (raf != null) {
                raf.close();
            }
        } catch (Exception ex) {
            logger.log(Level.WARNING, ErrorMessage.GENERAL_READ_FAILED_UNABLE_TO_CLOSE_RANDOM_ACCESS_FILE.getMsg(f.getAbsolutePath()));
        }
    }
}
Also used : AudioFile(org.jaudiotagger.audio.AudioFile) RandomAccessFile(java.io.RandomAccessFile) CannotReadException(org.jaudiotagger.audio.exceptions.CannotReadException) Tag(org.jaudiotagger.tag.Tag) ReadOnlyFileException(org.jaudiotagger.audio.exceptions.ReadOnlyFileException) CannotReadException(org.jaudiotagger.audio.exceptions.CannotReadException) TagException(org.jaudiotagger.tag.TagException) InvalidAudioFrameException(org.jaudiotagger.audio.exceptions.InvalidAudioFrameException) IOException(java.io.IOException)

Example 14 with AudioFile

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

the class AudioFileWriter method delete.

/**
     * Delete the tag (if any) present in the given file
     *
     * @param af The file to process
     * @throws CannotWriteException if anything went wrong
     * @throws org.jaudiotagger.audio.exceptions.CannotReadException
     */
public 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) {
                    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) {
                    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);
        }
    }
}
Also used : CannotWriteException(org.jaudiotagger.audio.exceptions.CannotWriteException) RandomAccessFile(java.io.RandomAccessFile) 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)

Example 15 with AudioFile

use of org.jaudiotagger.audio.AudioFile in project JamsMusicPlayer by psaravan.

the class WriteToM3UPlaylist method getSongTitle.

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;
}
Also used : AudioFile(org.jaudiotagger.audio.AudioFile) CannotReadException(org.jaudiotagger.audio.exceptions.CannotReadException) TagException(org.jaudiotagger.tag.TagException) InvalidAudioFrameException(org.jaudiotagger.audio.exceptions.InvalidAudioFrameException) ReadOnlyFileException(org.jaudiotagger.audio.exceptions.ReadOnlyFileException) Tag(org.jaudiotagger.tag.Tag) IOException(java.io.IOException) AudioFile(org.jaudiotagger.audio.AudioFile) File(java.io.File)

Aggregations

AudioFile (org.jaudiotagger.audio.AudioFile)25 IOException (java.io.IOException)19 CannotReadException (org.jaudiotagger.audio.exceptions.CannotReadException)19 Tag (org.jaudiotagger.tag.Tag)19 File (java.io.File)18 InvalidAudioFrameException (org.jaudiotagger.audio.exceptions.InvalidAudioFrameException)17 ReadOnlyFileException (org.jaudiotagger.audio.exceptions.ReadOnlyFileException)17 TagException (org.jaudiotagger.tag.TagException)16 CannotWriteException (org.jaudiotagger.audio.exceptions.CannotWriteException)11 Cursor (android.database.Cursor)7 KeyNotFoundException (org.jaudiotagger.tag.KeyNotFoundException)5 ContentValues (android.content.ContentValues)4 FieldDataInvalidException (org.jaudiotagger.tag.FieldDataInvalidException)4 Paint (android.graphics.Paint)3 Query (com.simplecity.amp_library.model.Query)3 FileOutputStream (java.io.FileOutputStream)3 Intent (android.content.Intent)2 MediaStore (android.provider.MediaStore)2 NonNull (android.support.annotation.NonNull)2 DocumentFile (android.support.v4.provider.DocumentFile)2