Search in sources :

Example 21 with AudioFile

use of org.jaudiotagger.audio.AudioFile in project saga-android by AnandChowdhary.

the class DownloadReceiver method onReceive.

@Override
public void onReceive(final Context context, final Intent intent) {
    DownloadManager dMgr = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
    Long downloadId = intent.getExtras().getLong(DownloadManager.EXTRA_DOWNLOAD_ID);
    Cursor c = dMgr.query(new DownloadManager.Query().setFilterById(downloadId));
    if (c.moveToFirst()) {
        int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
        if (status == DownloadManager.STATUS_SUCCESSFUL) {
            final String title = c.getString(c.getColumnIndex(DownloadManager.COLUMN_TITLE));
            Log.d("Receiver", "Title:" + title);
            if (title.equalsIgnoreCase(context.getString(R.string.app_name) + " " + context.getString(R.string.update))) {
                Intent install = new Intent(Intent.ACTION_VIEW);
                install.setDataAndType(Uri.parse(c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI))), "application/vnd.android.package-archive");
                install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(install);
            } else {
                try {
                    TagOptionSingleton.getInstance().setAndroid(true);
                    final File file = new File(Utils.getStoragePath(context) + "/" + title);
                    final AudioFile f = AudioFileIO.read(file);
                    final Tag tag = f.getTag();
                    String json = readFromFile(context, title);
                    String url = null;
                    if (json != null) {
                        JSONObject jsonObject = new JSONObject(json);
                        if (jsonObject.getString("track") != null) {
                            if (jsonObject.getString("artist") != null) {
                                url = Utils.getAlbumArt(jsonObject.getString("track"), jsonObject.getString("artist"));
                            } else {
                                url = Utils.getAlbumArt(jsonObject.getString("track"), null);
                            }
                        }
                        if (jsonObject.getString("artist") != null)
                            tag.setField(FieldKey.ARTIST, jsonObject.getString("artist"));
                        if (jsonObject.getString("artist") != null)
                            tag.setField(FieldKey.ALBUM_ARTIST, jsonObject.getString("artist"));
                        if (jsonObject.getString("release") != null)
                            tag.setField(FieldKey.YEAR, jsonObject.getString("release"));
                        if (jsonObject.getString("trackno") != null)
                            tag.setField(FieldKey.TRACK, jsonObject.getString("trackno"));
                        if (jsonObject.getString("album") != null)
                            tag.setField(FieldKey.ALBUM, jsonObject.getString("album"));
                        if (jsonObject.getString("genre") != null)
                            tag.setField(FieldKey.GENRE, jsonObject.getString("genre"));
                        tag.setField(FieldKey.COMMENT, "Downloaded from Saga");
                    } else {
                        url = Utils.getAlbumArt(title.substring(0, title.length() - 4), null);
                    }
                    if (url != null) {
                        ImageRequest request = new ImageRequest(url, new Response.Listener<Bitmap>() {

                            @Override
                            public void onResponse(Bitmap bitmap) {
                                FileOutputStream out = null;
                                try {
                                    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
                                    String imageFileName = "JPEG_" + timeStamp + "_";
                                    File storageDir = context.getCacheDir();
                                    File cover = File.createTempFile(imageFileName, /* prefix */
                                    ".jpg", /* suffix */
                                    storageDir);
                                    out = new FileOutputStream(cover);
                                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
                                    AndroidArtwork artwork = AndroidArtwork.createArtworkFromFile(cover);
                                    tag.setField(artwork);
                                    Log.d(TAG, "AlbumArt deleted " + cover.delete());
                                } catch (Exception e) {
                                    e.printStackTrace();
                                } finally {
                                    commitAudio(context, f, file);
                                    try {
                                        if (out != null) {
                                            out.close();
                                        }
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }, 0, 0, null, new Response.ErrorListener() {

                            public void onErrorResponse(VolleyError error) {
                                error.printStackTrace();
                                commitAudio(context, f, file);
                            }
                        });
                        request.setShouldCache(false);
                        VolleySingleton.getInstance(context).addToRequestQueue(request);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
Also used : VolleyError(com.android.volley.VolleyError) Intent(android.content.Intent) IOException(java.io.IOException) Cursor(android.database.Cursor) DownloadManager(android.app.DownloadManager) Date(java.util.Date) CannotWriteException(org.jaudiotagger.audio.exceptions.CannotWriteException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) Response(com.android.volley.Response) AudioFile(org.jaudiotagger.audio.AudioFile) Bitmap(android.graphics.Bitmap) JSONObject(org.json.JSONObject) AndroidArtwork(org.jaudiotagger.tag.images.AndroidArtwork) ImageRequest(com.android.volley.toolbox.ImageRequest) FileOutputStream(java.io.FileOutputStream) Tag(org.jaudiotagger.tag.Tag) AudioFile(org.jaudiotagger.audio.AudioFile) File(java.io.File) SimpleDateFormat(java.text.SimpleDateFormat)

Example 22 with AudioFile

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

the class JaudiotaggerParser method setMetaData.

/**
     * Updates the given file with the given meta data.
     *
     * @param file     The music file to update.
     * @param metaData The new meta data.
     */
@Override
public void setMetaData(MediaFile file, MetaData metaData) {
    try {
        AudioFile audioFile = AudioFileIO.read(file.getFile());
        Tag tag = audioFile.getTagOrCreateAndSetDefault();
        tag.setField(FieldKey.ARTIST, StringUtils.trimToEmpty(metaData.getArtist()));
        tag.setField(FieldKey.ALBUM, StringUtils.trimToEmpty(metaData.getAlbumName()));
        tag.setField(FieldKey.TITLE, StringUtils.trimToEmpty(metaData.getTitle()));
        tag.setField(FieldKey.GENRE, StringUtils.trimToEmpty(metaData.getGenre()));
        try {
            tag.setField(FieldKey.ALBUM_ARTIST, StringUtils.trimToEmpty(metaData.getAlbumArtist()));
        } catch (Exception x) {
        // Silently ignored. ID3v1 doesn't support album artist.
        }
        Integer track = metaData.getTrackNumber();
        if (track == null) {
            tag.deleteField(FieldKey.TRACK);
        } else {
            tag.setField(FieldKey.TRACK, String.valueOf(track));
        }
        Integer year = metaData.getYear();
        if (year == null) {
            tag.deleteField(FieldKey.YEAR);
        } else {
            tag.setField(FieldKey.YEAR, String.valueOf(year));
        }
        audioFile.commit();
    } catch (Throwable x) {
        LOG.warn("Failed to update tags for file " + file, x);
        throw new RuntimeException("Failed to update tags for file " + file + ". " + x.getMessage(), x);
    }
}
Also used : AudioFile(org.jaudiotagger.audio.AudioFile) Tag(org.jaudiotagger.tag.Tag)

Example 23 with AudioFile

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

the class TaggerDialog method populateViews.

void populateViews() {
    if (originalSongPaths == null || originalSongPaths.isEmpty()) {
        return;
    }
    try {
        AudioFile mAudioFile = AudioFileIO.read(new File(originalSongPaths.get(0)));
        Tag tag = mAudioFile.getTag();
        if (tag == null) {
            return;
        }
        title = tag.getFirst(FieldKey.TITLE);
        albumName = tag.getFirst(FieldKey.ALBUM);
        artistName = tag.getFirst(FieldKey.ARTIST);
        try {
            albumArtistName = tag.getFirst(FieldKey.ALBUM_ARTIST);
        } catch (UnsupportedOperationException ignored) {
        }
        genre = tag.getFirst(FieldKey.GENRE);
        year = tag.getFirst(FieldKey.YEAR);
        track = tag.getFirst(FieldKey.TRACK);
        try {
            trackTotal = tag.getFirst(FieldKey.TRACK_TOTAL);
        } catch (UnsupportedOperationException ignored) {
        }
        try {
            disc = tag.getFirst(FieldKey.DISC_NO);
        } catch (UnsupportedOperationException ignored) {
        }
        try {
            discTotal = tag.getFirst(FieldKey.DISC_TOTAL);
        } catch (UnsupportedOperationException ignored) {
        }
        try {
            lyrics = tag.getFirst(FieldKey.LYRICS);
        } catch (UnsupportedOperationException ignored) {
        }
        try {
            comment = tag.getFirst(FieldKey.COMMENT);
        } catch (UnsupportedOperationException ignored) {
        }
    } catch (IOException | InvalidAudioFrameException | TagException | ReadOnlyFileException | CannotReadException e) {
        Log.e(TAG, "Failed to read tags. " + e.toString());
    }
    titleEditText.setText(title);
    titleEditText.setSelection(titleEditText.getText().length());
    titleEditText.addTextChangedListener(new CustomTextWatcher(titleEditText, textChangeListener));
    albumEditText.setText(albumName);
    albumEditText.setSelection(albumEditText.getText().length());
    albumEditText.addTextChangedListener(new CustomTextWatcher(titleEditText, textChangeListener));
    artistEditText.setText(artistName);
    artistEditText.setSelection(artistEditText.getText().length());
    artistEditText.addTextChangedListener(new CustomTextWatcher(artistEditText, textChangeListener));
    albumArtistEditText.setText(albumArtistName);
    albumArtistEditText.setSelection(albumArtistEditText.getText().length());
    albumArtistEditText.addTextChangedListener(new CustomTextWatcher(albumArtistEditText, textChangeListener));
    genreEditText.setText(genre);
    genreEditText.setSelection(genreEditText.getText().length());
    genreEditText.addTextChangedListener(new CustomTextWatcher(genreEditText, textChangeListener));
    yearEditText.setText(String.valueOf(year));
    yearEditText.setSelection(yearEditText.getText().length());
    yearEditText.addTextChangedListener(new CustomTextWatcher(yearEditText, textChangeListener));
    trackEditText.setText(String.valueOf(track));
    trackEditText.setSelection(trackEditText.getText().length());
    trackEditText.addTextChangedListener(new CustomTextWatcher(trackEditText, textChangeListener));
    trackTotalEditText.setText(String.valueOf(trackTotal));
    trackTotalEditText.setSelection(trackTotalEditText.getText().length());
    trackTotalEditText.addTextChangedListener(new CustomTextWatcher(trackTotalEditText, textChangeListener));
    discEditText.setText(String.valueOf(disc));
    discEditText.setSelection(discEditText.getText().length());
    discEditText.addTextChangedListener(new CustomTextWatcher(discEditText, textChangeListener));
    discTotalEditText.setText(String.valueOf(discTotal));
    discTotalEditText.setSelection(discTotalEditText.getText().length());
    discTotalEditText.addTextChangedListener(new CustomTextWatcher(discTotalEditText, textChangeListener));
    lyricsEditText.setText(lyrics);
    lyricsEditText.setSelection(lyricsEditText.getText().length());
    lyricsEditText.addTextChangedListener(new CustomTextWatcher(lyricsEditText, textChangeListener));
    commentEditText.setText(comment);
    commentEditText.setSelection(commentEditText.getText().length());
    commentEditText.addTextChangedListener(new CustomTextWatcher(commentEditText, textChangeListener));
}
Also used : AudioFile(org.jaudiotagger.audio.AudioFile) TagException(org.jaudiotagger.tag.TagException) CannotReadException(org.jaudiotagger.audio.exceptions.CannotReadException) 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) DocumentFile(android.support.v4.provider.DocumentFile)

Example 24 with AudioFile

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

the class TaggerTask method doInBackground.

@Override
protected Boolean doInBackground(Object... params) {
    boolean success = false;
    boolean requiresPermission = TaggerUtils.requiresPermission(paths);
    for (int i = 0; i < paths.size(); i++) {
        final String path = paths.get(i);
        try {
            File orig = new File(path);
            AudioFile audioFile = AudioFileIO.read(orig);
            Tag tag = audioFile.getTag();
            if (tag == null) {
                break;
            }
            TagUpdate tagUpdate = new TagUpdate(tag);
            tagUpdate.softSetArtist(artistText);
            tagUpdate.softSetAlbumArtist(albumArtistText);
            tagUpdate.softSetGenre(genreText);
            tagUpdate.softSetYear(yearText);
            if (showAlbum) {
                tagUpdate.softSetAlbum(albumText);
                tagUpdate.softSetDiscTotal(discTotalText);
            }
            if (showTrack) {
                tagUpdate.softSetTitle(titleText);
                tagUpdate.softSetTrack(trackText);
                tagUpdate.softSetTrackTotal(trackTotalText);
                tagUpdate.softSetDisc(discText);
                tagUpdate.softSetLyrics(lyricsText);
                tagUpdate.softSetComment(commentText);
            }
            File temp = null;
            if (tagUpdate.hasChanged()) {
                if (TaggerUtils.requiresPermission(paths)) {
                    temp = new File(ShuttleApplication.getInstance().getFilesDir(), orig.getName());
                    tempFiles.add(temp);
                    TaggerUtils.copyFile(orig, temp);
                    audioFile = AudioFileIO.read(temp);
                    tag = audioFile.getTag();
                    if (tag == null) {
                        break;
                    }
                }
                tagUpdate.updateTag(tag);
                AudioFileIO.write(audioFile);
                if (requiresPermission && temp != null) {
                    DocumentFile documentFile = documentFiles.get(i);
                    if (documentFile != null) {
                        ParcelFileDescriptor pfd = ShuttleApplication.getInstance().getContentResolver().openFileDescriptor(documentFile.getUri(), "w");
                        if (pfd != null) {
                            FileOutputStream fileOutputStream = new FileOutputStream(pfd.getFileDescriptor());
                            TaggerUtils.copyFile(temp, fileOutputStream);
                            pfd.close();
                        }
                        if (temp.delete()) {
                            if (tempFiles.contains(temp)) {
                                tempFiles.remove(temp);
                            }
                        }
                    }
                }
            }
            publishProgress(i);
            success = true;
        } catch (CannotWriteException | IOException | CannotReadException | InvalidAudioFrameException | TagException | ReadOnlyFileException e) {
            e.printStackTrace();
        } finally {
            // Try to clean up our temp files
            if (tempFiles != null && tempFiles.size() != 0) {
                for (int j = tempFiles.size() - 1; j >= 0; j--) {
                    File file = tempFiles.get(j);
                    file.delete();
                    tempFiles.remove(j);
                }
            }
        }
    }
    return success;
}
Also used : CannotWriteException(org.jaudiotagger.audio.exceptions.CannotWriteException) DocumentFile(android.support.v4.provider.DocumentFile) CannotReadException(org.jaudiotagger.audio.exceptions.CannotReadException) InvalidAudioFrameException(org.jaudiotagger.audio.exceptions.InvalidAudioFrameException) IOException(java.io.IOException) TagUpdate(com.simplecity.amp_library.model.TagUpdate) AudioFile(org.jaudiotagger.audio.AudioFile) TagException(org.jaudiotagger.tag.TagException) FileOutputStream(java.io.FileOutputStream) ParcelFileDescriptor(android.os.ParcelFileDescriptor) ReadOnlyFileException(org.jaudiotagger.audio.exceptions.ReadOnlyFileException) Tag(org.jaudiotagger.tag.Tag) File(java.io.File) AudioFile(org.jaudiotagger.audio.AudioFile) DocumentFile(android.support.v4.provider.DocumentFile)

Example 25 with AudioFile

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

the class LyricsPresenter method updateLyrics.

private void updateLyrics() {
    addDisposable(Observable.fromCallable(() -> {
        String lyrics = "";
        String path = MusicUtils.getFilePath();
        if (TextUtils.isEmpty(path)) {
            return lyrics;
        }
        if (path.startsWith("content://")) {
            Query query = new Query.Builder().uri(Uri.parse(path)).projection(new String[] { MediaStore.Audio.Media.DATA }).build();
            Cursor cursor = SqlUtils.createQuery(ShuttleApplication.getInstance(), query);
            if (cursor != null) {
                try {
                    int colIndex = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
                    if (cursor.moveToFirst()) {
                        path = cursor.getString(colIndex);
                    }
                } finally {
                    cursor.close();
                }
            }
        }
        File file = new File(path);
        if (file.exists()) {
            try {
                AudioFile audioFile = AudioFileIO.read(file);
                if (audioFile != null) {
                    Tag tag = audioFile.getTag();
                    if (tag != null) {
                        String tagLyrics = tag.getFirst(FieldKey.LYRICS);
                        if (tagLyrics != null && tagLyrics.length() != 0) {
                            lyrics = tagLyrics.replace("\r", "\n");
                        }
                    }
                }
            } catch (CannotReadException | IOException | TagException | ReadOnlyFileException | InvalidAudioFrameException | UnsupportedOperationException ignored) {
            }
        }
        return lyrics;
    }).subscribe(lyrics -> {
        LyricsView lyricsView = getView();
        if (lyricsView != null) {
            lyricsView.updateLyrics(lyrics);
            lyricsView.showNoLyricsView(TextUtils.isEmpty(lyrics));
            lyricsView.showQuickLyricInfoButton(!QuickLyricUtils.isQLInstalled());
        }
    }, error -> LogUtils.logException(TAG, "Error getting lyrics", error)));
}
Also used : ReadOnlyFileException(org.jaudiotagger.audio.exceptions.ReadOnlyFileException) CannotReadException(org.jaudiotagger.audio.exceptions.CannotReadException) Uri(android.net.Uri) NonNull(android.support.annotation.NonNull) Song(com.simplecity.amp_library.model.Song) AudioFile(org.jaudiotagger.audio.AudioFile) MediaStore(android.provider.MediaStore) Observable(io.reactivex.Observable) Cursor(android.database.Cursor) FieldKey(org.jaudiotagger.tag.FieldKey) LogUtils(com.simplecity.amp_library.utils.LogUtils) BackpressureStrategy(io.reactivex.BackpressureStrategy) IntentFilter(android.content.IntentFilter) TextUtils(android.text.TextUtils) IOException(java.io.IOException) Tag(org.jaudiotagger.tag.Tag) RxBroadcast(com.cantrowitz.rxbroadcast.RxBroadcast) File(java.io.File) Query(com.simplecity.amp_library.model.Query) Presenter(com.simplecity.amp_library.ui.presenters.Presenter) MusicUtils(com.simplecity.amp_library.utils.MusicUtils) ShuttleApplication(com.simplecity.amp_library.ShuttleApplication) MusicService(com.simplecity.amp_library.playback.MusicService) TagException(org.jaudiotagger.tag.TagException) AudioFileIO(org.jaudiotagger.audio.AudioFileIO) InvalidAudioFrameException(org.jaudiotagger.audio.exceptions.InvalidAudioFrameException) SqlUtils(com.simplecity.amp_library.sql.SqlUtils) Query(com.simplecity.amp_library.model.Query) CannotReadException(org.jaudiotagger.audio.exceptions.CannotReadException) InvalidAudioFrameException(org.jaudiotagger.audio.exceptions.InvalidAudioFrameException) IOException(java.io.IOException) Cursor(android.database.Cursor) 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)

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