Search in sources :

Example 11 with Tag

use of org.jaudiotagger.tag.Tag 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 12 with Tag

use of org.jaudiotagger.tag.Tag 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 13 with Tag

use of org.jaudiotagger.tag.Tag in project MusicDNA by harjot-oberai.

the class AudioFile method getTagOrCreateAndSetDefault.

/**
     * Get the tag or if the file doesn'timer have one at all, create a default tag and set it
     *
     * @return
     */
public Tag getTagOrCreateAndSetDefault() {
    Tag tag = getTagOrCreateDefault();
    setTag(tag);
    return tag;
}
Also used : FlacTag(org.jaudiotagger.tag.flac.FlacTag) RealTag(org.jaudiotagger.audio.real.RealTag) Tag(org.jaudiotagger.tag.Tag) VorbisCommentTag(org.jaudiotagger.tag.vorbiscomment.VorbisCommentTag) AiffTag(org.jaudiotagger.audio.aiff.AiffTag) Mp4Tag(org.jaudiotagger.tag.mp4.Mp4Tag) AsfTag(org.jaudiotagger.tag.asf.AsfTag) WavTag(org.jaudiotagger.audio.wav.WavTag)

Example 14 with Tag

use of org.jaudiotagger.tag.Tag 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)

Example 15 with Tag

use of org.jaudiotagger.tag.Tag in project JamsMusicPlayer by psaravan.

the class AsyncAutoGetAlbumArtTask method doInBackground.

@Override
protected Void doInBackground(String... params) {
    //First, we'll go through all the songs in the music library DB and get their attributes.
    dbHelper = new DBAccessHelper(mContext);
    String selection = DBAccessHelper.SONG_SOURCE + "<>" + "'GOOGLE_PLAY_MUSIC'";
    String[] projection = { DBAccessHelper._ID, DBAccessHelper.SONG_FILE_PATH, DBAccessHelper.SONG_ALBUM, DBAccessHelper.SONG_ARTIST, DBAccessHelper.SONG_TITLE };
    Cursor cursor = dbHelper.getWritableDatabase().query(DBAccessHelper.MUSIC_LIBRARY_TABLE, projection, selection, null, null, null, null);
    if (cursor.getCount() != 0) {
        cursor.moveToFirst();
        dataURIsList.add(cursor.getString(1));
        albumsList.add(cursor.getString(2));
        artistsList.add(cursor.getString(3));
        while (cursor.moveToNext()) {
            dataURIsList.add(cursor.getString(1));
            albumsList.add(cursor.getString(2));
            artistsList.add(cursor.getString(3));
        }
    } else {
        //The user doesn't have any music so let's get outta here.
        return null;
    }
    pd.setMax(dataURIsList.size());
    //Now that we have the attributes of the songs, we'll go through them each and check for missing covers.
    for (int i = 0; i < dataURIsList.size(); i++) {
        try {
            file = new File(dataURIsList.get(i));
        } catch (Exception e) {
            continue;
        }
        audioFile = null;
        try {
            audioFile = AudioFileIO.read(file);
        } catch (CannotReadException e2) {
            // TODO Auto-generated catch block
            continue;
        } catch (IOException e2) {
            // TODO Auto-generated catch block
            continue;
        } catch (TagException e2) {
            // TODO Auto-generated catch block
            continue;
        } catch (ReadOnlyFileException e2) {
            // TODO Auto-generated catch block
            continue;
        } catch (InvalidAudioFrameException e2) {
            // TODO Auto-generated catch block
            continue;
        }
        Tag tag = audioFile.getTag();
        //Set the destination directory for the xml file.
        File SDCardRoot = Environment.getExternalStorageDirectory();
        File xmlFile = new File(SDCardRoot, "albumArt.xml");
        if (tag != null) {
            String title = tag.getFirst(FieldKey.TITLE);
            String checkingMessage = mContext.getResources().getString(R.string.checking_if) + " " + title + " " + mContext.getResources().getString(R.string.has_album_art) + ".";
            currentProgress = currentProgress + 1;
            String[] checkingProgressParams = { checkingMessage, "" + currentProgress };
            publishProgress(checkingProgressParams);
            List<Artwork> artworkList = tag.getArtworkList();
            if (artworkList.size() == 0) {
                //Since the file doesn't have any album artwork, we'll have to download it.
                //Get the artist and album name of the file we're working with.
                String artist = tag.getFirst(FieldKey.ARTIST);
                String album = tag.getFirst(FieldKey.ALBUM);
                //Update the progress dialog.
                String message = mContext.getResources().getString(R.string.downloading_artwork_for) + " " + title;
                String[] progressParams = { message, "" + currentProgress };
                publishProgress(progressParams);
                //Remove any unacceptable characters.
                if (artist.contains("#")) {
                    artist = artist.replace("#", "");
                }
                if (artist.contains("$")) {
                    artist = artist.replace("$", "");
                }
                if (artist.contains("@")) {
                    artist = artist.replace("@", "");
                }
                if (album.contains("#")) {
                    album = album.replace("#", "");
                }
                if (album.contains("$")) {
                    album = album.replace("$", "");
                }
                if (album.contains("@")) {
                    album = album.replace("@", "");
                }
                //Replace any spaces in the artist and album fields with "%20".
                if (artist.contains(" ")) {
                    artist = artist.replace(" ", "%20");
                }
                if (album.contains(" ")) {
                    album = album.replace(" ", "%20");
                }
                //Construct the url for the HTTP request.
                URL url = null;
                try {
                    url = new URL("http://itunes.apple.com/search?term=" + artist + "+" + album + "&entity=album");
                } catch (MalformedURLException e1) {
                    // TODO Auto-generated catch block
                    continue;
                }
                String xml = null;
                try {
                    //Create a new HTTP connection.
                    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                    urlConnection.connect();
                    //Check if albumArt.xml already exists and delete it.
                    if (xmlFile.exists()) {
                        xmlFile.delete();
                    }
                    //Create the OuputStream that will be used to store the downloaded data into the file.
                    FileOutputStream fileOutput = new FileOutputStream(xmlFile);
                    //Create the InputStream that will read the data from the HTTP connection.
                    InputStream inputStream = urlConnection.getInputStream();
                    //Total size of target file.
                    int totalSize = urlConnection.getContentLength();
                    //Temp variable that stores the number of downloaded bytes.
                    int downloadedSize = 0;
                    //Create a buffer to store the downloaded bytes.
                    buffer = new byte[1024];
                    int bufferLength = 0;
                    //Now read through the buffer and write the contents to the file.
                    while ((bufferLength = inputStream.read(buffer)) > 0) {
                        fileOutput.write(buffer, 0, bufferLength);
                        downloadedSize += bufferLength;
                    }
                    //Close the File Output Stream.
                    fileOutput.close();
                } catch (MalformedURLException e) {
                    //TODO Auto-generated method stub
                    continue;
                } catch (IOException e) {
                    // TODO Auto-generated method stub
                    continue;
                }
                //Load the XML file into a String variable for local use.
                String xmlAsString = null;
                try {
                    xmlAsString = FileUtils.readFileToString(xmlFile);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                //Extract the albumArt parameter from the XML file.
                artworkURL = StringUtils.substringBetween(xmlAsString, "\"artworkUrl100\":\"", "\",");
                if (artworkURL == null) {
                    //Check and see if a lower resolution image available.
                    artworkURL = StringUtils.substringBetween(xmlAsString, "\"artworkUrl60\":\"", "\",");
                    if (artworkURL == null) {
                    //Can't do anything about that here.
                    } else {
                        //Replace "100x100" with "600x600" to retrieve larger album art images.
                        artworkURL = artworkURL.replace("100x100", "600x600");
                    }
                } else {
                    //Replace "100x100" with "600x600" to retrieve larger album art images.
                    artworkURL = artworkURL.replace("100x100", "600x600");
                }
                //If no URL has been found, there's no point in continuing.
                if (artworkURL != null) {
                    artworkBitmap = null;
                    artworkBitmap = mApp.getImageLoader().loadImageSync(artworkURL);
                    File artworkFile = new File(Environment.getExternalStorageDirectory() + "/artwork.jpg");
                    //Save the artwork.
                    try {
                        FileOutputStream out = new FileOutputStream(artworkFile);
                        artworkBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        Artwork artwork = null;
                        try {
                            artwork = ArtworkFactory.createArtworkFromFile(artworkFile);
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            setArtworkAsFile(artworkFile, dataURIsList.get(i));
                            continue;
                        } catch (ArrayIndexOutOfBoundsException e) {
                            // TODO Auto-generated catch block
                            setArtworkAsFile(artworkFile, dataURIsList.get(i));
                            continue;
                        } catch (Exception e) {
                            e.printStackTrace();
                            setArtworkAsFile(artworkFile, dataURIsList.get(i));
                            continue;
                        } catch (Error e) {
                            e.printStackTrace();
                            setArtworkAsFile(artworkFile, dataURIsList.get(i));
                            continue;
                        }
                        if (artwork != null) {
                            try {
                                //Remove the current artwork field and recreate it.
                                tag.deleteArtworkField();
                                tag.addField(artwork);
                            } catch (Exception e) {
                                // TODO Auto-generated catch block
                                setArtworkAsFile(artworkFile, dataURIsList.get(i));
                                continue;
                            } catch (Error e) {
                                e.printStackTrace();
                                setArtworkAsFile(artworkFile, dataURIsList.get(i));
                                continue;
                            }
                            try {
                                audioFile.commit();
                            } catch (CannotWriteException e) {
                                // TODO Auto-generated catch block
                                setArtworkAsFile(artworkFile, dataURIsList.get(i));
                                continue;
                            } catch (Error e) {
                                e.printStackTrace();
                                setArtworkAsFile(artworkFile, dataURIsList.get(i));
                                continue;
                            }
                        }
                        //Delete the temporary files that we stored during the fetching process.
                        if (artworkFile.exists()) {
                            artworkFile.delete();
                        }
                        if (xmlFile.exists()) {
                            xmlFile.delete();
                        }
                        //Set the files to null to help clean up memory.
                        artworkBitmap = null;
                        audioFile = null;
                        tag = null;
                        xmlFile = null;
                        artworkFile = null;
                    }
                }
            }
        }
    }
    audioFile = null;
    file = null;
    return null;
}
Also used : CannotWriteException(org.jaudiotagger.audio.exceptions.CannotWriteException) MalformedURLException(java.net.MalformedURLException) Artwork(org.jaudiotagger.tag.images.Artwork) CannotReadException(org.jaudiotagger.audio.exceptions.CannotReadException) DBAccessHelper(com.jams.music.player.DBHelpers.DBAccessHelper) InputStream(java.io.InputStream) InvalidAudioFrameException(org.jaudiotagger.audio.exceptions.InvalidAudioFrameException) IOException(java.io.IOException) Cursor(android.database.Cursor) ReadOnlyFileException(org.jaudiotagger.audio.exceptions.ReadOnlyFileException) CannotReadException(org.jaudiotagger.audio.exceptions.CannotReadException) CannotWriteException(org.jaudiotagger.audio.exceptions.CannotWriteException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) TagException(org.jaudiotagger.tag.TagException) InvalidAudioFrameException(org.jaudiotagger.audio.exceptions.InvalidAudioFrameException) URL(java.net.URL) HttpURLConnection(java.net.HttpURLConnection) TagException(org.jaudiotagger.tag.TagException) FileOutputStream(java.io.FileOutputStream) ReadOnlyFileException(org.jaudiotagger.audio.exceptions.ReadOnlyFileException) Tag(org.jaudiotagger.tag.Tag) AudioFile(org.jaudiotagger.audio.AudioFile) File(java.io.File)

Aggregations

Tag (org.jaudiotagger.tag.Tag)23 AudioFile (org.jaudiotagger.audio.AudioFile)21 IOException (java.io.IOException)17 CannotReadException (org.jaudiotagger.audio.exceptions.CannotReadException)16 InvalidAudioFrameException (org.jaudiotagger.audio.exceptions.InvalidAudioFrameException)16 ReadOnlyFileException (org.jaudiotagger.audio.exceptions.ReadOnlyFileException)16 File (java.io.File)15 TagException (org.jaudiotagger.tag.TagException)15 Cursor (android.database.Cursor)7 CannotWriteException (org.jaudiotagger.audio.exceptions.CannotWriteException)7 ContentValues (android.content.ContentValues)5 MediaStore (android.provider.MediaStore)4 NonNull (android.support.annotation.NonNull)4 Query (com.simplecity.amp_library.model.Query)4 AudioFileIO (org.jaudiotagger.audio.AudioFileIO)4 ContentUris (android.content.ContentUris)3 Log (android.util.Log)3 FileOutputStream (java.io.FileOutputStream)3 FieldDataInvalidException (org.jaudiotagger.tag.FieldDataInvalidException)3 Manifest (android.Manifest)2