Search in sources :

Example 16 with CannotReadException

use of org.jaudiotagger.audio.exceptions.CannotReadException in project JamsMusicPlayer by psaravan.

the class ID3sSongEditorDialog method onCreateDialog.

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    mContext = getActivity();
    parentActivity = getActivity();
    dialogFragment = this;
    rootView = (View) parentActivity.getLayoutInflater().inflate(R.layout.fragment_edit_id3_artist_album_dialog, null);
    titleText = (TextView) rootView.findViewById(R.id.edit_title_text);
    artistText = (TextView) rootView.findViewById(R.id.edit_artist_text);
    albumText = (TextView) rootView.findViewById(R.id.edit_album_text);
    albumArtistText = (TextView) rootView.findViewById(R.id.edit_album_artist_text);
    genreText = (TextView) rootView.findViewById(R.id.edit_genre_text);
    producerText = (TextView) rootView.findViewById(R.id.edit_producer_text);
    yearText = (TextView) rootView.findViewById(R.id.edit_year_text);
    trackText = (TextView) rootView.findViewById(R.id.edit_track_text);
    ofText = (TextView) rootView.findViewById(R.id.text_of);
    commentsText = (TextView) rootView.findViewById(R.id.edit_comment_text);
    titleEditText = (EditText) rootView.findViewById(R.id.edit_title_field);
    artistEditText = (EditText) rootView.findViewById(R.id.edit_artist_field);
    albumEditText = (EditText) rootView.findViewById(R.id.edit_album_field);
    albumArtistEditText = (EditText) rootView.findViewById(R.id.edit_album_artist_field);
    genreEditText = (EditText) rootView.findViewById(R.id.edit_genre_field);
    producerEditText = (EditText) rootView.findViewById(R.id.edit_producer_field);
    yearEditText = (EditText) rootView.findViewById(R.id.edit_year_field);
    trackEditText = (EditText) rootView.findViewById(R.id.edit_track_field);
    trackTotalEditText = (EditText) rootView.findViewById(R.id.edit_track_total_field);
    commentsEditText = (EditText) rootView.findViewById(R.id.edit_comment_field);
    titleCheckbox = (CheckBox) rootView.findViewById(R.id.title_checkbox);
    artistCheckbox = (CheckBox) rootView.findViewById(R.id.artist_checkbox);
    albumCheckbox = (CheckBox) rootView.findViewById(R.id.album_checkbox);
    albumArtistCheckbox = (CheckBox) rootView.findViewById(R.id.album_artist_checkbox);
    genreCheckbox = (CheckBox) rootView.findViewById(R.id.genre_checkbox);
    producerCheckbox = (CheckBox) rootView.findViewById(R.id.producer_checkbox);
    yearCheckbox = (CheckBox) rootView.findViewById(R.id.year_checkbox);
    trackCheckbox = (CheckBox) rootView.findViewById(R.id.track_checkbox);
    commentCheckbox = (CheckBox) rootView.findViewById(R.id.comment_checkbox);
    titleText.setTypeface(TypefaceHelper.getTypeface(parentActivity, "RobotoCondensed-Light"));
    artistText.setTypeface(TypefaceHelper.getTypeface(parentActivity, "RobotoCondensed-Light"));
    albumText.setTypeface(TypefaceHelper.getTypeface(parentActivity, "RobotoCondensed-Light"));
    albumArtistText.setTypeface(TypefaceHelper.getTypeface(parentActivity, "RobotoCondensed-Light"));
    genreText.setTypeface(TypefaceHelper.getTypeface(parentActivity, "RobotoCondensed-Light"));
    producerText.setTypeface(TypefaceHelper.getTypeface(parentActivity, "RobotoCondensed-Light"));
    yearText.setTypeface(TypefaceHelper.getTypeface(parentActivity, "RobotoCondensed-Light"));
    trackText.setTypeface(TypefaceHelper.getTypeface(parentActivity, "RobotoCondensed-Light"));
    ofText.setTypeface(TypefaceHelper.getTypeface(parentActivity, "RobotoCondensed-Light"));
    commentsText.setTypeface(TypefaceHelper.getTypeface(parentActivity, "RobotoCondensed-Light"));
    titleText.setPaintFlags(titleText.getPaintFlags() | Paint.ANTI_ALIAS_FLAG | Paint.SUBPIXEL_TEXT_FLAG | Paint.FAKE_BOLD_TEXT_FLAG);
    artistText.setPaintFlags(titleText.getPaintFlags() | Paint.ANTI_ALIAS_FLAG | Paint.SUBPIXEL_TEXT_FLAG | Paint.FAKE_BOLD_TEXT_FLAG);
    albumText.setPaintFlags(titleText.getPaintFlags() | Paint.ANTI_ALIAS_FLAG | Paint.SUBPIXEL_TEXT_FLAG | Paint.FAKE_BOLD_TEXT_FLAG);
    albumArtistText.setPaintFlags(titleText.getPaintFlags() | Paint.ANTI_ALIAS_FLAG | Paint.SUBPIXEL_TEXT_FLAG | Paint.FAKE_BOLD_TEXT_FLAG);
    genreText.setPaintFlags(titleText.getPaintFlags() | Paint.ANTI_ALIAS_FLAG | Paint.SUBPIXEL_TEXT_FLAG | Paint.FAKE_BOLD_TEXT_FLAG);
    producerText.setPaintFlags(titleText.getPaintFlags() | Paint.ANTI_ALIAS_FLAG | Paint.SUBPIXEL_TEXT_FLAG | Paint.FAKE_BOLD_TEXT_FLAG);
    yearText.setPaintFlags(titleText.getPaintFlags() | Paint.ANTI_ALIAS_FLAG | Paint.SUBPIXEL_TEXT_FLAG | Paint.FAKE_BOLD_TEXT_FLAG);
    trackText.setPaintFlags(titleText.getPaintFlags() | Paint.ANTI_ALIAS_FLAG | Paint.SUBPIXEL_TEXT_FLAG | Paint.FAKE_BOLD_TEXT_FLAG);
    ofText.setPaintFlags(titleText.getPaintFlags() | Paint.ANTI_ALIAS_FLAG | Paint.SUBPIXEL_TEXT_FLAG | Paint.FAKE_BOLD_TEXT_FLAG);
    commentsText.setPaintFlags(titleText.getPaintFlags() | Paint.ANTI_ALIAS_FLAG | Paint.SUBPIXEL_TEXT_FLAG | Paint.FAKE_BOLD_TEXT_FLAG);
    titleEditText.setTypeface(TypefaceHelper.getTypeface(parentActivity, "RobotoCondensed-Light"));
    artistEditText.setTypeface(TypefaceHelper.getTypeface(parentActivity, "RobotoCondensed-Light"));
    albumEditText.setTypeface(TypefaceHelper.getTypeface(parentActivity, "RobotoCondensed-Light"));
    albumArtistEditText.setTypeface(TypefaceHelper.getTypeface(parentActivity, "RobotoCondensed-Light"));
    genreEditText.setTypeface(TypefaceHelper.getTypeface(parentActivity, "RobotoCondensed-Light"));
    producerEditText.setTypeface(TypefaceHelper.getTypeface(parentActivity, "RobotoCondensed-Light"));
    yearEditText.setTypeface(TypefaceHelper.getTypeface(parentActivity, "RobotoCondensed-Light"));
    trackEditText.setTypeface(TypefaceHelper.getTypeface(parentActivity, "RobotoCondensed-Light"));
    trackTotalEditText.setTypeface(TypefaceHelper.getTypeface(parentActivity, "RobotoCondensed-Light"));
    commentsEditText.setTypeface(TypefaceHelper.getTypeface(parentActivity, "RobotoCondensed-Light"));
    titleEditText.setPaintFlags(titleText.getPaintFlags() | Paint.ANTI_ALIAS_FLAG | Paint.SUBPIXEL_TEXT_FLAG);
    artistEditText.setPaintFlags(titleText.getPaintFlags() | Paint.ANTI_ALIAS_FLAG | Paint.SUBPIXEL_TEXT_FLAG);
    albumEditText.setPaintFlags(titleText.getPaintFlags() | Paint.ANTI_ALIAS_FLAG | Paint.SUBPIXEL_TEXT_FLAG);
    albumArtistEditText.setPaintFlags(titleText.getPaintFlags() | Paint.ANTI_ALIAS_FLAG | Paint.SUBPIXEL_TEXT_FLAG);
    genreEditText.setPaintFlags(titleText.getPaintFlags() | Paint.ANTI_ALIAS_FLAG | Paint.SUBPIXEL_TEXT_FLAG);
    producerEditText.setPaintFlags(titleText.getPaintFlags() | Paint.ANTI_ALIAS_FLAG | Paint.SUBPIXEL_TEXT_FLAG);
    yearEditText.setPaintFlags(titleText.getPaintFlags() | Paint.ANTI_ALIAS_FLAG | Paint.SUBPIXEL_TEXT_FLAG);
    trackEditText.setPaintFlags(titleText.getPaintFlags() | Paint.ANTI_ALIAS_FLAG | Paint.SUBPIXEL_TEXT_FLAG);
    trackTotalEditText.setPaintFlags(titleText.getPaintFlags() | Paint.ANTI_ALIAS_FLAG | Paint.SUBPIXEL_TEXT_FLAG);
    commentsEditText.setPaintFlags(titleText.getPaintFlags() | Paint.ANTI_ALIAS_FLAG | Paint.SUBPIXEL_TEXT_FLAG);
    //Keep all the fields locked by default.
    titleCheckbox.setChecked(false);
    artistCheckbox.setChecked(false);
    albumCheckbox.setChecked(false);
    albumArtistCheckbox.setChecked(false);
    genreCheckbox.setChecked(false);
    producerCheckbox.setChecked(false);
    yearCheckbox.setChecked(false);
    trackCheckbox.setChecked(false);
    commentCheckbox.setChecked(false);
    //Disable all EditTexts by default.
    titleEditText.setEnabled(false);
    artistEditText.setEnabled(false);
    albumEditText.setEnabled(false);
    albumArtistEditText.setEnabled(false);
    genreEditText.setEnabled(false);
    producerEditText.setEnabled(false);
    yearEditText.setEnabled(false);
    trackEditText.setEnabled(false);
    commentsEditText.setEnabled(false);
    //Register click registers on each checkbox.
    titleCheckbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton checkbox, boolean checked) {
            if (checked == true) {
                titleEdited = true;
                titleEditText.setEnabled(true);
            } else {
                titleEdited = false;
                titleEditText.setEnabled(false);
            }
        }
    });
    artistCheckbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton checkbox, boolean checked) {
            if (checked == true) {
                artistEdited = true;
                artistEditText.setEnabled(true);
                ;
            } else {
                artistEdited = false;
                artistEditText.setEnabled(false);
            }
        }
    });
    albumArtistCheckbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton checkbox, boolean checked) {
            if (checked == true) {
                albumEdited = true;
                albumEditText.setEnabled(true);
                ;
            } else {
                albumEdited = false;
                albumEditText.setEnabled(false);
            }
        }
    });
    albumCheckbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton checkbox, boolean checked) {
            if (checked == true) {
                albumArtistEdited = true;
                albumArtistEditText.setEnabled(true);
                ;
            } else {
                albumArtistEdited = false;
                albumArtistEditText.setEnabled(false);
            }
        }
    });
    genreCheckbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton checkbox, boolean checked) {
            if (checked == true) {
                genreEdited = true;
                genreEditText.setEnabled(true);
                ;
            } else {
                genreEdited = false;
                genreEditText.setEnabled(false);
            }
        }
    });
    producerCheckbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton checkbox, boolean checked) {
            if (checked == true) {
                producerEdited = true;
                producerEditText.setEnabled(true);
                ;
            } else {
                producerEdited = false;
                producerEditText.setEnabled(false);
            }
        }
    });
    yearCheckbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton checkbox, boolean checked) {
            if (checked == true) {
                yearEdited = true;
                yearEditText.setEnabled(true);
                ;
            } else {
                yearEdited = false;
                yearEditText.setEnabled(false);
            }
        }
    });
    trackCheckbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton checkbox, boolean checked) {
            if (checked == true) {
                trackEdited = true;
                trackEditText.setEnabled(true);
                ;
            } else {
                trackEdited = false;
                trackEditText.setEnabled(false);
            }
        }
    });
    commentCheckbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton checkbox, boolean checked) {
            if (checked == true) {
                commentEdited = true;
                commentsEditText.setEnabled(true);
                ;
            } else {
                commentEdited = false;
                commentsEditText.setEnabled(false);
            }
        }
    });
    //Get the song uri.
    SONG_URI = getArguments().getString("SONG");
    //Get the calling Fragment and retrieve the child view from it.
    CALLING_FRAGMENT = getArguments().getString("CALLING_FRAGMENT");
    if (SONG_URI != null) {
        //Populate the ArrayLists with the song tags.
        try {
            getSongTags(SONG_URI);
        } 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();
        }
    }
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    //Set the dialog title.
    builder.setTitle(R.string.edit_tags);
    builder.setView(rootView);
    builder.setPositiveButton(R.string.save, new OnClickListener() {

        @Override
        public void onClick(DialogInterface arg0, int arg1) {
            dialogFragment.dismiss();
            boolean saveSucceeded = saveSongTags(SONG_URI);
            //Check if the write operations succeeded. If they didn't, display an error message.
            if (saveSucceeded == true) {
                Toast.makeText(getActivity().getApplicationContext(), R.string.song_tags_saved, Toast.LENGTH_SHORT).show();
            /*					//Reinitialize the calling fragment.
					if (CALLING_FRAGMENT.equals("SONGS_FRAGMENT")) {


					} else if (CALLING_FRAGMENT.equals("ARTISTS_FLIPPED_SONGS_FRAGMENT")) {
						//ArtistsFlippedSongsFragment.getCursor();
						ArtistsFlippedSongsFragment.songsListViewAdapter.notifyDataSetChanged();
					} else if (CALLING_FRAGMENT.equals("ALBUMS_FLIPPED_FRAGMENT")) {
						AlbumsFlippedFragment.getCursor();
						AlbumsFlippedFragment.albumsFlippedListViewAdapter.notifyDataSetChanged();
					} else if (CALLING_FRAGMENT.equals("ALBUM_ARTISTS_FLIPPED_SONGS_FRAGMENT")) {
						AlbumArtistsFlippedSongsFragment.getCursor();
						AlbumArtistsFlippedSongsFragment.songsListViewAdapter.notifyDataSetChanged();
					} else if (CALLING_FRAGMENT.equals("GENRES_FLIPPED_SONGS_FRAGMENT")) {
						GenresFlippedFragment.getCursor();
						GenresFlippedFragment.genresFlippedListViewAdapter.notifyDataSetChanged();
					}*/
            } else {
                Toast.makeText(parentActivity, R.string.error_occurred_tags, Toast.LENGTH_LONG).show();
            }
        }
    });
    builder.setNegativeButton(R.string.cancel, new OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });
    return builder.create();
}
Also used : AlertDialog(android.app.AlertDialog) OnCheckedChangeListener(android.widget.CompoundButton.OnCheckedChangeListener) CannotReadException(org.jaudiotagger.audio.exceptions.CannotReadException) DialogInterface(android.content.DialogInterface) InvalidAudioFrameException(org.jaudiotagger.audio.exceptions.InvalidAudioFrameException) IOException(java.io.IOException) Paint(android.graphics.Paint) TagException(org.jaudiotagger.tag.TagException) ReadOnlyFileException(org.jaudiotagger.audio.exceptions.ReadOnlyFileException) OnClickListener(android.content.DialogInterface.OnClickListener) CompoundButton(android.widget.CompoundButton)

Example 17 with CannotReadException

use of org.jaudiotagger.audio.exceptions.CannotReadException in project JamsMusicPlayer by psaravan.

the class ID3sSongEditorDialog method saveSongTags.

//This method is called if the user touches the 'OK' button when they're editing an individual song's tags.
public boolean saveSongTags(String uri) {
    File file = new File(uri);
    AudioFile audioFile = null;
    //Update the DB entries.
    DBAccessHelper dbHelper = new DBAccessHelper(mContext.getApplicationContext());
    //Escape any rogue apostrophes.
    if (SONG_URI.contains("'")) {
        SONG_URI = SONG_URI.replace("'", "''");
    }
    String whereClause = DBAccessHelper.SONG_FILE_PATH + "=" + "'" + SONG_URI + "'";
    ContentValues values = new ContentValues();
    try {
        audioFile = AudioFileIO.read(file);
    } 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 tag = audioFile.getTag();
    if (tag != null) {
        if (titleEdited == false) {
        //Don't do anything here. The user didn't change the title.
        } else {
            try {
                tag.setField(FieldKey.TITLE, titleEditText.getText().toString());
            } catch (KeyNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (FieldDataInvalidException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (NoSuchElementException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            String title = titleEditText.getText().toString();
            if (title.contains("'")) {
                title = title.replace("'", "''");
            }
            values.put(DBAccessHelper.SONG_TITLE, title);
        }
        if (albumEdited == false) {
        //Don't do anything here. The user didn't change the album.
        } else {
            try {
                tag.setField(FieldKey.ALBUM, albumEditText.getText().toString());
            } catch (KeyNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (FieldDataInvalidException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (NoSuchElementException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            String album = albumEditText.getText().toString();
            if (album.contains("'")) {
                album = album.replace("'", "''");
            }
            values.put(DBAccessHelper.SONG_ALBUM, album);
        }
        if (artistEdited == false) {
        //Don't do anything here. The user didn't change the artist.
        } else {
            try {
                tag.setField(FieldKey.ARTIST, artistEditText.getText().toString());
            } catch (KeyNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (FieldDataInvalidException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (NoSuchElementException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            String artist = artistEditText.getText().toString();
            if (artist.contains("'")) {
                artist = artist.replace("'", "''");
            }
            values.put(DBAccessHelper.SONG_ARTIST, artist);
        }
        if (albumArtistEdited == false) {
        //Don't do anything here. The user didn't change the album artist.
        } else {
            try {
                tag.setField(FieldKey.ALBUM_ARTIST, albumArtistEditText.getText().toString());
            } catch (KeyNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (FieldDataInvalidException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (NoSuchElementException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            String albumArtist = albumArtistEditText.getText().toString();
            if (albumArtist.contains("'")) {
                albumArtist = albumArtist.replace("'", "''");
            }
            values.put(DBAccessHelper.SONG_ALBUM_ARTIST, albumArtist);
        }
        if (genreEdited == false) {
        //Don't do anything here. The user didn't change the genre.
        } else {
            try {
                tag.setField(FieldKey.GENRE, genreEditText.getText().toString());
            } catch (KeyNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (FieldDataInvalidException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (NoSuchElementException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if (producerEdited == false) {
        //Don't do anything here. The user didn't change the producer.
        } else {
            try {
                tag.setField(FieldKey.PRODUCER, producerEditText.getText().toString());
            } catch (KeyNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (FieldDataInvalidException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (NoSuchElementException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if (yearEdited == false) {
        //Don't do anything here. The user didn't change the year.
        } else {
            try {
                tag.setField(FieldKey.YEAR, yearEditText.getText().toString());
            } catch (KeyNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (FieldDataInvalidException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (NoSuchElementException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (NumberFormatException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            String year = yearEditText.getText().toString();
            if (year.contains("'")) {
                year = year.replace("'", "''");
            }
            values.put(DBAccessHelper.SONG_YEAR, year);
        }
        if (trackEdited == false) {
        //Don't do anything here. The user didn't change the track number.
        } else {
            try {
                tag.setField(FieldKey.TRACK, trackEditText.getText().toString());
            } catch (KeyNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (FieldDataInvalidException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (NoSuchElementException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (NumberFormatException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            String track = trackEditText.getText().toString();
            if (track.contains("'")) {
                track = track.replace("'", "''");
            }
            values.put(DBAccessHelper.SONG_TRACK_NUMBER, track);
        }
        try {
            tag.setField(FieldKey.TRACK_TOTAL, trackTotalEditText.getText().toString());
        } catch (KeyNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (FieldDataInvalidException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchElementException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NumberFormatException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if (commentEdited == false) {
        //Don't do anything here. The user didn't change the comments.
        } else {
            try {
                tag.setField(FieldKey.COMMENT, commentsEditText.getText().toString());
            } catch (KeyNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (FieldDataInvalidException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (NoSuchElementException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        try {
            audioFile.commit();
        } catch (CannotWriteException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //Write the values to the DB.
        if (values.size() != 0) {
            //Write the values to the DB.
            try {
                dbHelper.getWritableDatabase().update(DBAccessHelper.MUSIC_LIBRARY_TABLE, values, whereClause, null);
                dbHelper.close();
                dbHelper = null;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    } else {
        Toast.makeText(mContext, R.string.unable_to_edit_song_tags, Toast.LENGTH_SHORT).show();
    }
    return true;
}
Also used : ContentValues(android.content.ContentValues) CannotWriteException(org.jaudiotagger.audio.exceptions.CannotWriteException) CannotReadException(org.jaudiotagger.audio.exceptions.CannotReadException) DBAccessHelper(com.jams.music.player.DBHelpers.DBAccessHelper) InvalidAudioFrameException(org.jaudiotagger.audio.exceptions.InvalidAudioFrameException) IOException(java.io.IOException) ReadOnlyFileException(org.jaudiotagger.audio.exceptions.ReadOnlyFileException) CannotReadException(org.jaudiotagger.audio.exceptions.CannotReadException) FieldDataInvalidException(org.jaudiotagger.tag.FieldDataInvalidException) NoSuchElementException(java.util.NoSuchElementException) CannotWriteException(org.jaudiotagger.audio.exceptions.CannotWriteException) KeyNotFoundException(org.jaudiotagger.tag.KeyNotFoundException) IOException(java.io.IOException) TagException(org.jaudiotagger.tag.TagException) InvalidAudioFrameException(org.jaudiotagger.audio.exceptions.InvalidAudioFrameException) AudioFile(org.jaudiotagger.audio.AudioFile) TagException(org.jaudiotagger.tag.TagException) FieldDataInvalidException(org.jaudiotagger.tag.FieldDataInvalidException) ReadOnlyFileException(org.jaudiotagger.audio.exceptions.ReadOnlyFileException) Tag(org.jaudiotagger.tag.Tag) AudioFile(org.jaudiotagger.audio.AudioFile) File(java.io.File) KeyNotFoundException(org.jaudiotagger.tag.KeyNotFoundException) NoSuchElementException(java.util.NoSuchElementException)

Example 18 with CannotReadException

use of org.jaudiotagger.audio.exceptions.CannotReadException in project JamsMusicPlayer by psaravan.

the class PlaylistPagerFlippedFragment method onCreateView.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    final ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_playlist_pager_flipped, container, false);
    mContext = getActivity().getApplicationContext();
    mApp = (Common) mContext;
    ratingBar = (RatingBar) rootView.findViewById(R.id.playlist_pager_flipped_rating_bar);
    lyricsRelativeLayout = (RelativeLayout) rootView.findViewById(R.id.lyricsRelativeLayout);
    lyricsTextView = (TextView) rootView.findViewById(R.id.playlist_pager_flipped_lyrics);
    headerTextView = (TextView) rootView.findViewById(R.id.playlist_pager_flipped_title);
    noLyricsFoundText = (TextView) rootView.findViewById(R.id.no_embedded_lyrics_found_text);
    lyricsTextView.setTypeface(TypefaceHelper.getTypeface(mContext, "RobotoCondensed-Light"));
    lyricsTextView.setPaintFlags(lyricsTextView.getPaintFlags() | Paint.ANTI_ALIAS_FLAG | Paint.SUBPIXEL_TEXT_FLAG);
    headerTextView.setTypeface(TypefaceHelper.getTypeface(mContext, "RobotoCondensed-Light"));
    headerTextView.setPaintFlags(headerTextView.getPaintFlags() | Paint.ANTI_ALIAS_FLAG | Paint.SUBPIXEL_TEXT_FLAG);
    noLyricsFoundText.setTypeface(TypefaceHelper.getTypeface(mContext, "RobotoCondensed-Light"));
    noLyricsFoundText.setPaintFlags(noLyricsFoundText.getPaintFlags() | Paint.ANTI_ALIAS_FLAG | Paint.SUBPIXEL_TEXT_FLAG);
    lyricsRelativeLayout.setOnLongClickListener(new OnLongClickListener() {

        @Override
        public boolean onLongClick(View arg0) {
            //Fire a broadcast that notifies the PlaylistPager to update flip back to the album art.
            Intent intent = new Intent(broadcastMessage);
            intent.putExtra("MESSAGE", broadcastMessage);
            //Initialize the local broadcast manager.
            localBroadcastManager = LocalBroadcastManager.getInstance(mContext);
            localBroadcastManager.sendBroadcast(intent);
            return true;
        }
    });
    //Get the file path of the current song.
    String updatedSongTitle = "";
    String updatedSongArtist = "";
    String songFilePath = "";
    String songId = "";
    MediaMetadataRetriever mmdr = new MediaMetadataRetriever();
    tempCursor = mApp.getService().getCursor();
    tempCursor.moveToPosition(mApp.getService().getPlaybackIndecesList().get(mApp.getService().getCurrentSongIndex()));
    if (tempCursor.getColumnIndex(DBAccessHelper.SONG_FILE_PATH) == -1) {
        //Retrieve the info from the file's metadata.
        songFilePath = tempCursor.getString(tempCursor.getColumnIndex(null));
        mmdr.setDataSource(songFilePath);
        updatedSongTitle = mmdr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE);
        updatedSongArtist = mmdr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST);
    } else {
        /* Check if the cursor has the SONG_FILE_PATH column. If it does, we're dealing 
			 * with the SONGS table. If not, we're dealing with the PLAYLISTS table. We'll 
			 * retrieve data from the appropriate columns using this info. */
        if (tempCursor.getColumnIndex(DBAccessHelper.SONG_FILE_PATH) == -1) {
            //We're dealing with the Playlists table.
            songFilePath = tempCursor.getString(tempCursor.getColumnIndex(DBAccessHelper.PLAYLIST_FILE_PATH));
            mmdr.setDataSource(songFilePath);
            updatedSongTitle = mmdr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE);
            updatedSongArtist = mmdr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST);
        } else {
            //We're dealing with the songs table.
            songFilePath = tempCursor.getString(tempCursor.getColumnIndex(DBAccessHelper.SONG_FILE_PATH));
            updatedSongTitle = tempCursor.getString(tempCursor.getColumnIndex(DBAccessHelper.SONG_TITLE));
            updatedSongArtist = tempCursor.getString(tempCursor.getColumnIndex(DBAccessHelper.SONG_ARTIST));
            songId = tempCursor.getString(tempCursor.getColumnIndex(DBAccessHelper.SONG_ID));
        }
    }
    headerTextView.setText(updatedSongTitle + " - " + updatedSongArtist);
    ratingBar.setStepSize(1);
    int rating = mApp.getDBAccessHelper().getSongRating(songId);
    ratingBar.setRating(rating);
    //Get the rating value for the song.
    AudioFile audioFile = null;
    File file = null;
    try {
        audioFile = null;
        file = new File(songFilePath);
        try {
            audioFile = AudioFileIO.read(file);
        } catch (CannotReadException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (org.jaudiotagger.tag.TagException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (ReadOnlyFileException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (InvalidAudioFrameException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    try {
        final AudioFile finalizedAudioFile = audioFile;
        final String finalSongFilePath = songFilePath;
        final String finalSongId = songId;
        ratingBar.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {

            @Override
            public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
                //Change the rating in the DB and the actual audio file itself.
                Log.e("DEBUG", ">>>>>RATING: " + rating);
                try {
                    Tag tag = finalizedAudioFile.getTag();
                    tag.addField(FieldKey.RATING, "" + ((int) rating));
                } catch (KeyNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (FieldDataInvalidException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.e("DEBUG", ">>>>>>>RATING FIELD NOT FOUND");
                }
                try {
                    finalizedAudioFile.commit();
                } catch (CannotWriteException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                mApp.getDBAccessHelper().setSongRating(finalSongId, (int) rating);
            }
        });
        //Check if the audio file has any embedded lyrics.
        String lyrics = null;
        try {
            Tag tag = audioFile.getTag();
            lyrics = tag.getFirst(FieldKey.LYRICS);
            if (lyrics == null || lyrics.isEmpty()) {
                lyricsTextView.setVisibility(View.GONE);
                noLyricsFoundText.setVisibility(View.VISIBLE);
                return rootView;
            }
            //Since the song has embedded lyrics, display them in the layout.
            lyricsTextView.setVisibility(View.VISIBLE);
            noLyricsFoundText.setVisibility(View.GONE);
            lyricsTextView.setText(lyrics);
        } catch (Exception e) {
            e.printStackTrace();
            lyricsTextView.setVisibility(View.GONE);
            noLyricsFoundText.setVisibility(View.VISIBLE);
            return rootView;
        }
    } catch (Exception e) {
        e.printStackTrace();
    //Can't do much here.
    }
    return rootView;
}
Also used : CannotWriteException(org.jaudiotagger.audio.exceptions.CannotWriteException) InvalidAudioFrameException(org.jaudiotagger.audio.exceptions.InvalidAudioFrameException) FieldDataInvalidException(org.jaudiotagger.tag.FieldDataInvalidException) OnLongClickListener(android.view.View.OnLongClickListener) ReadOnlyFileException(org.jaudiotagger.audio.exceptions.ReadOnlyFileException) CannotReadException(org.jaudiotagger.audio.exceptions.CannotReadException) OnRatingBarChangeListener(android.widget.RatingBar.OnRatingBarChangeListener) ViewGroup(android.view.ViewGroup) Intent(android.content.Intent) IOException(java.io.IOException) View(android.view.View) TextView(android.widget.TextView) RatingBar(android.widget.RatingBar) Paint(android.graphics.Paint) ReadOnlyFileException(org.jaudiotagger.audio.exceptions.ReadOnlyFileException) CannotReadException(org.jaudiotagger.audio.exceptions.CannotReadException) FieldDataInvalidException(org.jaudiotagger.tag.FieldDataInvalidException) CannotWriteException(org.jaudiotagger.audio.exceptions.CannotWriteException) KeyNotFoundException(org.jaudiotagger.tag.KeyNotFoundException) IOException(java.io.IOException) InvalidAudioFrameException(org.jaudiotagger.audio.exceptions.InvalidAudioFrameException) AudioFile(org.jaudiotagger.audio.AudioFile) MediaMetadataRetriever(android.media.MediaMetadataRetriever) Tag(org.jaudiotagger.tag.Tag) AudioFile(org.jaudiotagger.audio.AudioFile) File(java.io.File) KeyNotFoundException(org.jaudiotagger.tag.KeyNotFoundException)

Example 19 with CannotReadException

use of org.jaudiotagger.audio.exceptions.CannotReadException 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 20 with CannotReadException

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

the class Mp4TagWriter method write.

/**
        * Write tag to rafTemp file
        *
        * @param tag     tag data
        * @param raf     current file
        * @param rafTemp temporary file for writing
        * @throws CannotWriteException
        * @throws IOException
        */
public void write(Tag tag, RandomAccessFile raf, RandomAccessFile rafTemp) throws CannotWriteException, IOException {
    logger.config("Started writing tag data");
    //Read Channel for reading from old file
    FileChannel fileReadChannel = raf.getChannel();
    //Write channel for writing to new file
    FileChannel fileWriteChannel = rafTemp.getChannel();
    //TODO we shouldn'timer need all these variables, and some are very badly named - used by new and old methods
    int oldIlstSize = 0;
    int relativeIlstposition;
    int startIlstWithinFile;
    int newIlstSize;
    int oldMetaLevelFreeAtomSize;
    int topLevelFreePosition;
    int topLevelFreeSize;
    long endOfMoov = 0;
    //Found top level free atom that comes after moov and before mdat, (also true if no free atom ?)
    boolean topLevelFreeAtomComesBeforeMdatAtomAndAfterMetadata;
    //Found top level free atom that comes between ftyp and moov
    boolean topLevelFreeAtomComesBeforeMdatAndMetadata;
    Mp4BoxHeader topLevelFreeHeader;
    Mp4AtomTree atomTree;
    //Build AtomTree
    try {
        atomTree = new Mp4AtomTree(raf, false);
    } catch (CannotReadException cre) {
        throw new CannotWriteException(cre.getMessage());
    }
    Mp4BoxHeader mdatHeader = atomTree.getBoxHeader(atomTree.getMdatNode());
    //Unable to find audio so no chance of saving any changes
    if (mdatHeader == null) {
        throw new CannotWriteException(ErrorMessage.MP4_CHANGES_TO_FILE_FAILED_CANNOT_FIND_AUDIO.getMsg());
    }
    //Go through every field constructing the data that will appear starting from ilst box
    ByteBuffer rawIlstData = tc.convert(tag);
    rawIlstData.rewind();
    newIlstSize = rawIlstData.limit();
    //Moov Box header
    Mp4BoxHeader moovHeader = atomTree.getBoxHeader(atomTree.getMoovNode());
    long positionWithinFileAfterFindingMoovHeader = moovHeader.getFilePos() + Mp4BoxHeader.HEADER_LENGTH;
    endOfMoov = moovHeader.getFilePos() + moovHeader.getLength();
    Mp4StcoBox stco = atomTree.getStco();
    Mp4BoxHeader ilstHeader = atomTree.getBoxHeader(atomTree.getIlstNode());
    Mp4BoxHeader udtaHeader = atomTree.getBoxHeader(atomTree.getUdtaNode());
    Mp4BoxHeader metaHeader = atomTree.getBoxHeader(atomTree.getMetaNode());
    Mp4BoxHeader hdlrMetaHeader = atomTree.getBoxHeader(atomTree.getHdlrWithinMetaNode());
    Mp4BoxHeader tagsHeader = atomTree.getBoxHeader(atomTree.getTagsNode());
    Mp4BoxHeader trakHeader = atomTree.getBoxHeader(atomTree.getTrakNodes().get(0));
    ByteBuffer moovBuffer = atomTree.getMoovBuffer();
    //Udta
    if (udtaHeader != null) {
        //Meta
        if (metaHeader != null) {
            //ilst - record where ilst is,and where it ends
            if (ilstHeader != null) {
                oldIlstSize = ilstHeader.getLength();
                //Relative means relative to moov buffer after moov header
                startIlstWithinFile = (int) ilstHeader.getFilePos();
                relativeIlstposition = (int) (startIlstWithinFile - (moovHeader.getFilePos() + Mp4BoxHeader.HEADER_LENGTH));
            } else {
                //Place ilst immediately after existing hdlr atom
                if (hdlrMetaHeader != null) {
                    startIlstWithinFile = (int) hdlrMetaHeader.getFilePos() + hdlrMetaHeader.getLength();
                    relativeIlstposition = (int) (startIlstWithinFile - (moovHeader.getFilePos() + Mp4BoxHeader.HEADER_LENGTH));
                } else //Place ilst after data fields in meta atom
                //TODO Should we create a hdlr atom
                {
                    startIlstWithinFile = (int) metaHeader.getFilePos() + Mp4BoxHeader.HEADER_LENGTH + Mp4MetaBox.FLAGS_LENGTH;
                    relativeIlstposition = (int) ((startIlstWithinFile) - (moovHeader.getFilePos() + Mp4BoxHeader.HEADER_LENGTH));
                }
            }
        } else {
            //There no ilst or meta header so we set to position where it would be if it existed
            relativeIlstposition = moovHeader.getLength() - Mp4BoxHeader.HEADER_LENGTH;
            startIlstWithinFile = (int) (moovHeader.getFilePos() + moovHeader.getLength());
        }
    } else //There no udta header so we are going to create a new structure, but we have to be aware that there might be
    //an existing meta box structure in which case we preserve it but with our new structure before it.
    {
        //Create new structure just after the end of the trak atom
        if (metaHeader != null) {
            startIlstWithinFile = (int) trakHeader.getFilePos() + trakHeader.getLength();
            relativeIlstposition = (int) (startIlstWithinFile - (moovHeader.getFilePos() + Mp4BoxHeader.HEADER_LENGTH));
        } else {
            //There no udta,ilst or meta header so we set to position where it would be if it existed
            relativeIlstposition = moovHeader.getLength() - Mp4BoxHeader.HEADER_LENGTH;
            startIlstWithinFile = (int) (moovHeader.getFilePos() + moovHeader.getLength());
        }
    }
    //Find size of Level-4 Free atom (if any) immediately after ilst atom
    oldMetaLevelFreeAtomSize = getMetaLevelFreeAtomSize(atomTree);
    //Level-1 free atom
    topLevelFreePosition = 0;
    topLevelFreeSize = 0;
    topLevelFreeAtomComesBeforeMdatAtomAndAfterMetadata = true;
    topLevelFreeAtomComesBeforeMdatAndMetadata = false;
    for (DefaultMutableTreeNode freeNode : atomTree.getFreeNodes()) {
        DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode) freeNode.getParent();
        if (parentNode.isRoot()) {
            topLevelFreeHeader = ((Mp4BoxHeader) freeNode.getUserObject());
            topLevelFreeSize = topLevelFreeHeader.getLength();
            topLevelFreePosition = (int) topLevelFreeHeader.getFilePos();
            break;
        }
    }
    if (topLevelFreeSize > 0) {
        if (topLevelFreePosition > mdatHeader.getFilePos()) {
            topLevelFreeAtomComesBeforeMdatAtomAndAfterMetadata = false;
        } else if (topLevelFreePosition < moovHeader.getFilePos()) {
            topLevelFreeAtomComesBeforeMdatAtomAndAfterMetadata = false;
            topLevelFreeAtomComesBeforeMdatAndMetadata = true;
        }
    } else {
        topLevelFreePosition = (int) mdatHeader.getFilePos();
    }
    logger.config("Read header successfully ready for writing");
    //create a new file identical to first file but with replaced metadata
    if (oldIlstSize == newIlstSize) {
        logger.config("Writing:Option 1:Same Size");
        writeMetadataSameSize(rawIlstData, oldIlstSize, startIlstWithinFile, fileReadChannel, fileWriteChannel, tagsHeader);
    } else //no other changes necessary and total file size remains the same
    if (oldIlstSize > newIlstSize) {
        //after ilst as a child of meta 
        if (oldMetaLevelFreeAtomSize > 0) {
            logger.config("Writing:Option 2:Smaller Size have free atom:" + oldIlstSize + ":" + newIlstSize);
            writeDataUptoIncludingIlst(fileReadChannel, fileWriteChannel, oldIlstSize, startIlstWithinFile, rawIlstData);
            //Write the modified free atom that comes after ilst
            int newFreeSize = oldMetaLevelFreeAtomSize + (oldIlstSize - newIlstSize);
            Mp4FreeBox newFreeBox = new Mp4FreeBox(newFreeSize - Mp4BoxHeader.HEADER_LENGTH);
            fileWriteChannel.write(newFreeBox.getHeader().getHeaderData());
            fileWriteChannel.write(newFreeBox.getData());
            //Skip over the read channel old free atom
            fileReadChannel.position(fileReadChannel.position() + oldMetaLevelFreeAtomSize);
            writeDataAfterIlst(fileReadChannel, fileWriteChannel, tagsHeader);
        } else //No free atom we need to create a new one or adjust top level free atom
        {
            int newFreeSize = (oldIlstSize - newIlstSize) - Mp4BoxHeader.HEADER_LENGTH;
            //into account size of new header in calculating size of box
            if (newFreeSize > 0) {
                logger.config("Writing:Option 3:Smaller Size can create free atom");
                writeDataUptoIncludingIlst(fileReadChannel, fileWriteChannel, oldIlstSize, startIlstWithinFile, rawIlstData);
                //Create new free box
                Mp4FreeBox newFreeBox = new Mp4FreeBox(newFreeSize);
                fileWriteChannel.write(newFreeBox.getHeader().getHeaderData());
                fileWriteChannel.write(newFreeBox.getData());
                writeDataAfterIlst(fileReadChannel, fileWriteChannel, tagsHeader);
            } else //Ok everything in this bit of tree has to be recalculated because eight or less bytes smaller
            {
                logger.config("Writing:Option 4:Smaller Size <=8 cannot create free atoms");
                //Size will be this amount smaller
                int sizeReducedBy = oldIlstSize - newIlstSize;
                //Write stuff before Moov (ftyp)
                fileReadChannel.position(0);
                fileWriteChannel.transferFrom(fileReadChannel, 0, moovHeader.getFilePos());
                fileWriteChannel.position(moovHeader.getFilePos());
                //unless mdat is at start of file
                if (mdatHeader.getFilePos() > moovHeader.getFilePos()) {
                    stco.adjustOffsets(-sizeReducedBy);
                }
                //Edit and rewrite the Moov,Udta and Meta header in moov buffer
                adjustSizeOfMoovHeader(moovHeader, moovBuffer, -sizeReducedBy, udtaHeader, metaHeader);
                fileWriteChannel.write(moovHeader.getHeaderData());
                moovBuffer.rewind();
                moovBuffer.limit(relativeIlstposition);
                fileWriteChannel.write(moovBuffer);
                //Now write ilst data
                fileWriteChannel.write(rawIlstData);
                fileReadChannel.position(startIlstWithinFile + oldIlstSize);
                writeDataAfterIlst(fileReadChannel, fileWriteChannel, tagsHeader);
            }
        }
    } else //Size of metadata has increased, the most complex situation, more atoms affected
    {
        int additionalSpaceRequiredForMetadata = newIlstSize - oldIlstSize;
        //solution where can fit in data, but cant fit in free atom header
        if (additionalSpaceRequiredForMetadata <= (oldMetaLevelFreeAtomSize - Mp4BoxHeader.HEADER_LENGTH)) {
            int newFreeSize = oldMetaLevelFreeAtomSize - (additionalSpaceRequiredForMetadata);
            logger.config("Writing:Option 5;Larger Size can use meta free atom need extra:" + newFreeSize + "bytes");
            writeDataUptoIncludingIlst(fileReadChannel, fileWriteChannel, oldIlstSize, startIlstWithinFile, rawIlstData);
            //Create an amended smaller freeBaos atom and write it to file
            Mp4FreeBox newFreeBox = new Mp4FreeBox(newFreeSize - Mp4BoxHeader.HEADER_LENGTH);
            fileWriteChannel.write(newFreeBox.getHeader().getHeaderData());
            fileWriteChannel.write(newFreeBox.getData());
            //Skip over the read channel old free atom
            fileReadChannel.position(fileReadChannel.position() + oldMetaLevelFreeAtomSize);
            writeDataAfterIlst(fileReadChannel, fileWriteChannel, tagsHeader);
        } else //There is not enough padding in the metadata free atom anyway
        //Size meta needs to be increased by (if not writing a free atom)
        //Special Case this could actually be negative (upto -8)if is actually enough space but would
        //not be able to write free atom properly, it doesn'timer matter the parent atoms would still
        //need their sizes adjusted.
        {
            int additionalMetaSizeThatWontFitWithinMetaAtom = additionalSpaceRequiredForMetadata - (oldMetaLevelFreeAtomSize);
            //Write stuff before Moov (ftyp)
            fileReadChannel.position(0);
            fileWriteChannel.transferFrom(fileReadChannel, 0, positionWithinFileAfterFindingMoovHeader - Mp4BoxHeader.HEADER_LENGTH);
            fileWriteChannel.position(positionWithinFileAfterFindingMoovHeader - Mp4BoxHeader.HEADER_LENGTH);
            if (udtaHeader == null) {
                logger.config("Writing:Option 5.1;No udta atom");
                Mp4HdlrBox hdlrBox = Mp4HdlrBox.createiTunesStyleHdlrBox();
                Mp4MetaBox metaBox = Mp4MetaBox.createiTunesStyleMetaBox(hdlrBox.getHeader().getLength() + rawIlstData.limit());
                udtaHeader = new Mp4BoxHeader(Mp4AtomIdentifier.UDTA.getFieldName());
                udtaHeader.setLength(Mp4BoxHeader.HEADER_LENGTH + metaBox.getHeader().getLength());
                additionalMetaSizeThatWontFitWithinMetaAtom = additionalMetaSizeThatWontFitWithinMetaAtom + (udtaHeader.getLength() - rawIlstData.limit());
                //or special case of matching exactly the free atom plus header)
                if ((!topLevelFreeAtomComesBeforeMdatAtomAndAfterMetadata) || ((topLevelFreeSize - Mp4BoxHeader.HEADER_LENGTH < additionalMetaSizeThatWontFitWithinMetaAtom) && (topLevelFreeSize != additionalMetaSizeThatWontFitWithinMetaAtom))) {
                    //by the amount mdat is going to be shifted
                    if (mdatHeader.getFilePos() > moovHeader.getFilePos()) {
                        logger.config("Adjusting Offsets");
                        stco.adjustOffsets(additionalMetaSizeThatWontFitWithinMetaAtom);
                    }
                }
                //Edit and rewrite the Moov header
                moovHeader.setLength(moovHeader.getLength() + additionalMetaSizeThatWontFitWithinMetaAtom);
                fileWriteChannel.write(moovHeader.getHeaderData());
                moovBuffer.rewind();
                moovBuffer.limit(relativeIlstposition);
                fileWriteChannel.write(moovBuffer);
                //Write new atoms required for holding metadata in itunes format
                fileWriteChannel.write(udtaHeader.getHeaderData());
                fileWriteChannel.write(metaBox.getHeader().getHeaderData());
                fileWriteChannel.write(metaBox.getData());
                fileWriteChannel.write(hdlrBox.getHeader().getHeaderData());
                fileWriteChannel.write(hdlrBox.getData());
            } else if (metaHeader == null) {
                //#291:In this case we throwaway editing udta header and create a new one, would be beter if we coul
                //keep the info but rather difficult.
                logger.config("Writing:Option 5.2;No meta atom");
                int oldUdtaHeaderLength = udtaHeader.getLength();
                Mp4HdlrBox hdlrBox = Mp4HdlrBox.createiTunesStyleHdlrBox();
                Mp4MetaBox metaBox = Mp4MetaBox.createiTunesStyleMetaBox(hdlrBox.getHeader().getLength() + rawIlstData.limit());
                udtaHeader = new Mp4BoxHeader(Mp4AtomIdentifier.UDTA.getFieldName());
                udtaHeader.setLength(Mp4BoxHeader.HEADER_LENGTH + metaBox.getHeader().getLength());
                additionalMetaSizeThatWontFitWithinMetaAtom = additionalMetaSizeThatWontFitWithinMetaAtom + (udtaHeader.getLength() - rawIlstData.limit());
                //or special case of matching exactly the free atom plus header)
                if ((!topLevelFreeAtomComesBeforeMdatAtomAndAfterMetadata) || ((topLevelFreeSize - Mp4BoxHeader.HEADER_LENGTH < additionalMetaSizeThatWontFitWithinMetaAtom) && (topLevelFreeSize != additionalMetaSizeThatWontFitWithinMetaAtom))) {
                    //by the amount mdat is going to be shifted
                    if (mdatHeader.getFilePos() > moovHeader.getFilePos()) {
                        logger.config("Adjusting Offsets");
                        stco.adjustOffsets(additionalMetaSizeThatWontFitWithinMetaAtom);
                    }
                }
                //Edit and rewrite the Moov header
                moovHeader.setLength(moovHeader.getLength() - oldUdtaHeaderLength + additionalMetaSizeThatWontFitWithinMetaAtom);
                fileWriteChannel.write(moovHeader.getHeaderData());
                moovBuffer.rewind();
                moovBuffer.limit(relativeIlstposition - oldUdtaHeaderLength);
                fileWriteChannel.write(moovBuffer);
                //Write new atoms required for holding metadata in itunes format
                fileWriteChannel.write(udtaHeader.getHeaderData());
                fileWriteChannel.write(metaBox.getHeader().getHeaderData());
                fileWriteChannel.write(metaBox.getData());
                fileWriteChannel.write(hdlrBox.getHeader().getHeaderData());
                fileWriteChannel.write(hdlrBox.getData());
            } else {
                logger.config("Writing:Option 5.3;udta atom exists");
                //or special case of matching exactly the free atom plus header)
                if ((!topLevelFreeAtomComesBeforeMdatAtomAndAfterMetadata) || ((topLevelFreeSize - Mp4BoxHeader.HEADER_LENGTH < additionalMetaSizeThatWontFitWithinMetaAtom) && (topLevelFreeSize != additionalMetaSizeThatWontFitWithinMetaAtom))) {
                    //by the amount mdat is going to be shifted
                    if (mdatHeader.getFilePos() > moovHeader.getFilePos()) {
                        stco.adjustOffsets(additionalMetaSizeThatWontFitWithinMetaAtom);
                    }
                }
                //Edit and rewrite the Moov header
                adjustSizeOfMoovHeader(moovHeader, moovBuffer, additionalMetaSizeThatWontFitWithinMetaAtom, udtaHeader, metaHeader);
                fileWriteChannel.write(moovHeader.getHeaderData());
                //Now write from this edited buffer up until ilst atom
                moovBuffer.rewind();
                moovBuffer.limit(relativeIlstposition);
                fileWriteChannel.write(moovBuffer);
            }
            //Now write ilst data
            fileWriteChannel.write(rawIlstData);
            //Skip over the read channel old meta level free atom because now used up
            fileReadChannel.position(startIlstWithinFile + oldIlstSize);
            fileReadChannel.position(fileReadChannel.position() + oldMetaLevelFreeAtomSize);
            if (tagsHeader != null) {
                //Write from after ilst upto tags atom
                long writeBetweenIlstAndTags = tagsHeader.getFilePos() - fileReadChannel.position();
                fileWriteChannel.transferFrom(fileReadChannel, fileWriteChannel.position(), writeBetweenIlstAndTags);
                fileWriteChannel.position(fileWriteChannel.position() + writeBetweenIlstAndTags);
                convertandWriteTagsAtomToFreeAtom(fileWriteChannel, tagsHeader);
                //Write after tags atom upto end of moov
                fileReadChannel.position(tagsHeader.getFilePos() + tagsHeader.getLength());
                long extraData = endOfMoov - fileReadChannel.position();
                fileWriteChannel.transferFrom(fileReadChannel, fileWriteChannel.position(), extraData);
            } else {
                //Now write the rest of children under moov which wont have changed
                long extraData = endOfMoov - fileReadChannel.position();
                fileWriteChannel.transferFrom(fileReadChannel, fileWriteChannel.position(), extraData);
                fileWriteChannel.position(fileWriteChannel.position() + extraData);
            }
            //the free atom actually come after the the metadata
            if (topLevelFreeAtomComesBeforeMdatAtomAndAfterMetadata && (topLevelFreePosition >= startIlstWithinFile)) {
                //ok
                if (topLevelFreeSize - Mp4BoxHeader.HEADER_LENGTH >= additionalMetaSizeThatWontFitWithinMetaAtom) {
                    logger.config("Writing:Option 6;Larger Size can use top free atom");
                    Mp4FreeBox freeBox = new Mp4FreeBox((topLevelFreeSize - Mp4BoxHeader.HEADER_LENGTH) - additionalMetaSizeThatWontFitWithinMetaAtom);
                    fileWriteChannel.write(freeBox.getHeader().getHeaderData());
                    fileWriteChannel.write(freeBox.getData());
                    //Skip over the read channel old free atom
                    fileReadChannel.position(fileReadChannel.position() + topLevelFreeSize);
                    //Write Mdat
                    writeDataInChunks(fileReadChannel, fileWriteChannel);
                } else //we could just remove the header
                if (topLevelFreeSize == additionalMetaSizeThatWontFitWithinMetaAtom) {
                    logger.config("Writing:Option 7;Larger Size uses top free atom including header");
                    //Skip over the read channel old free atom
                    fileReadChannel.position(fileReadChannel.position() + topLevelFreeSize);
                    //Write Mdat
                    writeDataInChunks(fileReadChannel, fileWriteChannel);
                } else //Mdat is going to have to move anyway, so keep free atom as is and write it and mdat
                //(have already updated stco above)
                {
                    logger.config("Writing:Option 8;Larger Size cannot use top free atom");
                    fileWriteChannel.transferFrom(fileReadChannel, fileWriteChannel.position(), fileReadChannel.size() - fileReadChannel.position());
                    writeDataInChunks(fileReadChannel, fileWriteChannel);
                }
            } else {
                logger.config("Writing:Option 9;Top Level Free comes after Mdat or before Metadata so cant use it");
                writeDataInChunks(fileReadChannel, fileWriteChannel);
            }
        }
    }
    //Close all channels to original file
    fileReadChannel.close();
    raf.close();
    checkFileWrittenCorrectly(rafTemp, mdatHeader, fileWriteChannel, stco);
}
Also used : CannotWriteException(org.jaudiotagger.audio.exceptions.CannotWriteException) DefaultMutableTreeNode(org.jaudiotagger.utils.tree.DefaultMutableTreeNode) CannotReadException(org.jaudiotagger.audio.exceptions.CannotReadException) FileChannel(java.nio.channels.FileChannel) ByteBuffer(java.nio.ByteBuffer)

Aggregations

CannotReadException (org.jaudiotagger.audio.exceptions.CannotReadException)39 InvalidAudioFrameException (org.jaudiotagger.audio.exceptions.InvalidAudioFrameException)23 ReadOnlyFileException (org.jaudiotagger.audio.exceptions.ReadOnlyFileException)23 TagException (org.jaudiotagger.tag.TagException)22 IOException (java.io.IOException)21 AudioFile (org.jaudiotagger.audio.AudioFile)18 File (java.io.File)15 Tag (org.jaudiotagger.tag.Tag)14 CannotWriteException (org.jaudiotagger.audio.exceptions.CannotWriteException)12 Cursor (android.database.Cursor)6 Paint (android.graphics.Paint)6 ByteBuffer (java.nio.ByteBuffer)5 FieldDataInvalidException (org.jaudiotagger.tag.FieldDataInvalidException)5 KeyNotFoundException (org.jaudiotagger.tag.KeyNotFoundException)5 ContentValues (android.content.ContentValues)4 GenericAudioHeader (org.jaudiotagger.audio.generic.GenericAudioHeader)4 OggPageHeader (org.jaudiotagger.audio.ogg.util.OggPageHeader)4 AlertDialog (android.app.AlertDialog)3 DialogInterface (android.content.DialogInterface)3 OnClickListener (android.content.DialogInterface.OnClickListener)3