Search in sources :

Example 31 with CannotReadException

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

the class AsfFileReader method getTag.

/**
     * (overridden)
     * 
     * @see org.jaudiotagger.audio.generic.AudioFileReader#getTag(java.io.RandomAccessFile)
     */
@Override
protected AsfTag getTag(final RandomAccessFile raf) throws CannotReadException, IOException {
    raf.seek(0);
    AsfTag tag;
    try {
        final AsfHeader header = AsfHeaderReader.readTagHeader(raf);
        if (header == null) {
            throw new CannotReadException("Some values must have been " + "incorrect for interpretation as asf with wma content.");
        }
        tag = TagConverter.createTagOf(header);
    } catch (final Exception e) {
        logger.severe(e.getMessage());
        if (e instanceof IOException) {
            throw (IOException) e;
        } else if (e instanceof CannotReadException) {
            throw (CannotReadException) e;
        } else {
            throw new CannotReadException("Failed to read. Cause: " + e.getMessage());
        }
    }
    return tag;
}
Also used : CannotReadException(org.jaudiotagger.audio.exceptions.CannotReadException) AsfTag(org.jaudiotagger.tag.asf.AsfTag) AsfHeader(org.jaudiotagger.audio.asf.data.AsfHeader) ReadOnlyFileException(org.jaudiotagger.audio.exceptions.ReadOnlyFileException) CannotReadException(org.jaudiotagger.audio.exceptions.CannotReadException) TagException(org.jaudiotagger.tag.TagException) InvalidAudioFrameException(org.jaudiotagger.audio.exceptions.InvalidAudioFrameException)

Example 32 with CannotReadException

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

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

the class ID3sAlbumEditorDialog method getSongTags.

//This method loops through all the songs and saves their tags into ArrayLists.
public void getSongTags(ArrayList<String> dataURIsList) throws CannotReadException, IOException, TagException, ReadOnlyFileException, InvalidAudioFrameException {
    Cursor cursor = null;
    for (int i = 0; i < dataURIsList.size(); i++) {
        //Check if the song is from Google Play Music.
        if (songSourcesList.get(i).equals(DBAccessHelper.GMUSIC)) {
            String songId = songIdsList.get(i);
            cursor = mApp.getDBAccessHelper().getSongById(songId);
            cursor.moveToFirst();
            titlesList.add(cursor.getString(cursor.getColumnIndex(DBAccessHelper.SONG_TITLE)));
            artistsList.add(cursor.getString(cursor.getColumnIndex(DBAccessHelper.SONG_ARTIST)));
            albumsList.add(cursor.getString(cursor.getColumnIndex(DBAccessHelper.SONG_ALBUM)));
            albumArtistsList.add(cursor.getString(cursor.getColumnIndex(DBAccessHelper.SONG_ALBUM_ARTIST)));
            genresList.add("");
            producersList.add("");
            yearsList.add(cursor.getString(cursor.getColumnIndex(DBAccessHelper.SONG_YEAR)));
            trackNumbersList.add(cursor.getString(cursor.getColumnIndex(DBAccessHelper.SONG_TRACK_NUMBER)));
            totalTracksList.add("");
            commentsList.add("");
        } else {
            File file = null;
            try {
                file = new File(dataURIsList.get(i));
            } catch (Exception e) {
                e.printStackTrace();
                continue;
            }
            AudioFile audioFile = AudioFileIO.read(file);
            titlesList.add(audioFile.getTag().getFirst(FieldKey.TITLE));
            artistsList.add(audioFile.getTag().getFirst(FieldKey.ARTIST));
            albumsList.add(audioFile.getTag().getFirst(FieldKey.ALBUM));
            albumArtistsList.add(audioFile.getTag().getFirst(FieldKey.ALBUM_ARTIST));
            genresList.add(audioFile.getTag().getFirst(FieldKey.GENRE));
            producersList.add(audioFile.getTag().getFirst(FieldKey.PRODUCER));
            yearsList.add(audioFile.getTag().getFirst(FieldKey.YEAR));
            trackNumbersList.add(audioFile.getTag().getFirst(FieldKey.TRACK));
            totalTracksList.add(audioFile.getTag().getFirst(FieldKey.TRACK_TOTAL));
            commentsList.add(audioFile.getTag().getFirst(FieldKey.COMMENT));
        }
    }
    if (cursor != null) {
        cursor.close();
        cursor = null;
    }
}
Also used : AudioFile(org.jaudiotagger.audio.AudioFile) Cursor(android.database.Cursor) AudioFile(org.jaudiotagger.audio.AudioFile) File(java.io.File) Paint(android.graphics.Paint) 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)

Example 34 with CannotReadException

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

the class ID3sArtistEditorDialog method onCreateDialog.

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    mContext = getActivity();
    parentActivity = getActivity();
    dialogFragment = this;
    //Get the artist name.
    ARTIST = getArguments().getString("ARTIST");
    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);
            }
        }
    });
    if (ARTIST != null) {
        songURIsList = getAllSongsByArtist(ARTIST);
        //Populate the ArrayLists with the song tags.
        try {
            getSongTags(songURIsList);
        } 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();
        }
        //Now check if any of the ArrayLists contain the same exact elements.
        boolean titlesSame = checkIfAllElementsEqual(titlesList);
        boolean artistsSame = checkIfAllElementsEqual(artistsList);
        boolean albumsSame = checkIfAllElementsEqual(albumsList);
        boolean albumArtistsSame = checkIfAllElementsEqual(albumArtistsList);
        boolean genresSame = checkIfAllElementsEqual(genresList);
        boolean producersSame = checkIfAllElementsEqual(producersList);
        boolean yearsSame = checkIfAllElementsEqual(yearsList);
        boolean tracksSame = checkIfAllElementsEqual(trackNumbersList);
        boolean totalTracksSame = checkIfAllElementsEqual(totalTracksList);
        boolean commentsSame = checkIfAllElementsEqual(commentsList);
        //Populate the EditTexts.
        setEditorFields(titlesSame, titlesList, titleEditText);
        setEditorFields(artistsSame, artistsList, artistEditText);
        setEditorFields(albumsSame, albumsList, albumEditText);
        setEditorFields(albumArtistsSame, albumArtistsList, albumArtistEditText);
        setEditorFields(genresSame, genresList, genreEditText);
        setEditorFields(producersSame, producersList, producerEditText);
        setEditorFields(yearsSame, yearsList, yearEditText);
        setEditorFields(tracksSame, trackNumbersList, trackEditText);
        setEditorFields(totalTracksSame, totalTracksList, trackTotalEditText);
        setEditorFields(commentsSame, commentsList, commentsEditText);
    }
    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();
            AsyncSaveArtistTagsTask asyncSaveArtistTagsTask = new AsyncSaveArtistTagsTask(getActivity(), getActivity());
            asyncSaveArtistTagsTask.execute();
        }
    });
    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 35 with CannotReadException

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

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