Search in sources :

Example 1 with CannotWriteException

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

the class AsyncGetAlbumArtTask method doInBackground.

@Override
protected Integer doInBackground(String... params) {
    //First, we'll make a HTTP request to iTunes' servers with the album and artist name.
    if (params.length == 2) {
        artist = params[0];
        album = params[1];
        //Create duplicate strings that will be filtered out for the URL.
        urlArtist = artist;
        urlAlbum = album;
        //Remove any unacceptable characters.
        if (urlArtist.contains("#")) {
            urlArtist = urlArtist.replace("#", "");
        }
        if (urlArtist.contains("$")) {
            urlArtist = urlArtist.replace("$", "");
        }
        if (urlArtist.contains("@")) {
            urlArtist = urlArtist.replace("@", "");
        }
        if (urlAlbum.contains("#")) {
            urlAlbum = urlAlbum.replace("#", "");
        }
        if (urlAlbum.contains("$")) {
            urlAlbum = urlAlbum.replace("$", "");
        }
        if (urlAlbum.contains("@")) {
            urlAlbum = urlAlbum.replace("@", "");
        }
        //Replace any spaces in the artist and album fields with "%20".
        if (urlArtist.contains(" ")) {
            urlArtist = urlArtist.replace(" ", "%20");
        }
        if (urlAlbum.contains(" ")) {
            urlAlbum = urlAlbum.replace(" ", "%20");
        }
    }
    //Construct the url for the HTTP request.
    URL uri = null;
    try {
        uri = new URL("http://itunes.apple.com/search?term=" + urlArtist + "+" + urlAlbum + "&entity=album");
    } catch (MalformedURLException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
        return 1;
    }
    try {
        //Create a new HTTP connection.
        HttpURLConnection urlConnection = (HttpURLConnection) uri.openConnection();
        urlConnection.connect();
        //Set the destination directory for the xml file.
        File SDCardRoot = Environment.getExternalStorageDirectory();
        file = new File(SDCardRoot, "albumArt.xml");
        //Create the OuputStream that will be used to store the downloaded data into the file.
        FileOutputStream fileOutput = new FileOutputStream(file);
        //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.
        byte[] 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
        e.printStackTrace();
        return 1;
    } catch (IOException e) {
        // TODO Auto-generated method stub
        e.printStackTrace();
        return 1;
    }
    //Create a File object that points to the downloaded file.
    File phpSource = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/albumArt.xml");
    String phpAsString = null;
    try {
        phpAsString = FileUtils.readFileToString(phpSource);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return 1;
    }
    //Extract the albumArt parameter from the PHP response.
    artworkURL = StringUtils.substringBetween(phpAsString, "\"artworkUrl100\":\"", "\",");
    if (artworkURL == null) {
        //Check and see if a lower resolution image available.
        artworkURL = StringUtils.substringBetween(phpAsString, "\"artworkUrl60\":\"", "\",");
        if (artworkURL == null) {
            URL_RETRIEVED = false;
            return 1;
        } else {
            //Replace "100x100" with "600x600" to retrieve larger album art images.
            artworkURL = artworkURL.replace("100x100", "600x600");
            URL_RETRIEVED = true;
        }
    } else {
        //Replace "100x100" with "600x600" to retrieve larger album art images.
        artworkURL = artworkURL.replace("100x100", "600x600");
        URL_RETRIEVED = true;
    }
    //Replace any rogue apostrophes.
    if (album.contains("'")) {
        album = album.replace("'", "''");
    }
    if (artist.contains("'")) {
        artist = artist.replace("'", "''");
    }
    String selection = DBAccessHelper.SONG_ALBUM + "=" + "'" + album + "'" + " AND " + DBAccessHelper.SONG_ARTIST + "=" + "'" + artist + "'";
    String[] projection = { DBAccessHelper._ID, DBAccessHelper.SONG_FILE_PATH };
    Cursor cursor = mApp.getDBAccessHelper().getWritableDatabase().query(DBAccessHelper.MUSIC_LIBRARY_TABLE, projection, selection, null, null, null, null);
    if (cursor.getCount() != 0) {
        cursor.moveToFirst();
        dataURIsList.add(cursor.getString(1));
        while (cursor.moveToNext()) {
            dataURIsList.add(cursor.getString(1));
        }
    }
    cursor.close();
    if (URL_RETRIEVED == true) {
        artworkBitmap = mApp.getImageLoader().loadImageSync(artworkURL);
        File artworkFile = new File(Environment.getExternalStorageDirectory() + "/artwork.jpg");
        //Display the album art on the grid/listview so that the user knows that the download is complete.
        publishProgress();
        //Save the artwork.
        try {
            FileOutputStream out = new FileOutputStream(artworkFile);
            artworkBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
            return 1;
        } finally {
            for (int i = 0; i < dataURIsList.size(); i++) {
                if (dataURIsList.get(i) != null) {
                    File audioFile = new File(dataURIsList.get(i));
                    AudioFile f = null;
                    try {
                        f = AudioFileIO.read(audioFile);
                    } 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 = null;
                    try {
                        if (f != null) {
                            tag = f.getTag();
                        } else {
                            continue;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        continue;
                    }
                    Artwork artwork = null;
                    try {
                        artwork = ArtworkFactory.createArtworkFromFile(artworkFile);
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        setArtworkAsFile(artworkFile, dataURIsList.get(i));
                        continue;
                    } catch (Error e) {
                        e.printStackTrace();
                        setArtworkAsFile(artworkFile, dataURIsList.get(i));
                        continue;
                    }
                    if (artwork != null) {
                        try {
                            tag.setField(artwork);
                        } catch (FieldDataInvalidException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                            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;
                        }
                    }
                    try {
                        f.commit();
                    } catch (CannotWriteException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        setArtworkAsFile(artworkFile, dataURIsList.get(i));
                        continue;
                    } catch (Error e) {
                        e.printStackTrace();
                        setArtworkAsFile(artworkFile, dataURIsList.get(i));
                        continue;
                    }
                    //Update the album art tag in Jams' database.
                    ContentValues values = new ContentValues();
                    String filePath = dataURIsList.get(i);
                    filePath = filePath.replace("'", "''");
                    String where = DBAccessHelper.SONG_FILE_PATH + "=" + "'" + filePath + "'";
                    values.put(DBAccessHelper.SONG_ALBUM_ART_PATH, "byte://" + dataURIsList.get(i));
                    mApp.getDBAccessHelper().getWritableDatabase().update(DBAccessHelper.MUSIC_LIBRARY_TABLE, values, where, null);
                } else {
                    continue;
                }
            }
            //Refresh the memory/disk cache for the ImageLoader instance.
            try {
                mApp.getImageLoader().clearMemoryCache();
                mApp.getImageLoader().clearDiscCache();
            } catch (Exception e) {
                e.printStackTrace();
            }
            //Delete the temporary files once the artwork has been embedded.
            artworkFile.delete();
            file.delete();
        }
    }
    return 0;
}
Also used : CannotWriteException(org.jaudiotagger.audio.exceptions.CannotWriteException) ContentValues(android.content.ContentValues) MalformedURLException(java.net.MalformedURLException) Artwork(org.jaudiotagger.tag.images.Artwork) CannotReadException(org.jaudiotagger.audio.exceptions.CannotReadException) InputStream(java.io.InputStream) InvalidAudioFrameException(org.jaudiotagger.audio.exceptions.InvalidAudioFrameException) IOException(java.io.IOException) Cursor(android.database.Cursor) URL(java.net.URL) ReadOnlyFileException(org.jaudiotagger.audio.exceptions.ReadOnlyFileException) CannotReadException(org.jaudiotagger.audio.exceptions.CannotReadException) FieldDataInvalidException(org.jaudiotagger.tag.FieldDataInvalidException) 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) AudioFile(org.jaudiotagger.audio.AudioFile) HttpURLConnection(java.net.HttpURLConnection) TagException(org.jaudiotagger.tag.TagException) FieldDataInvalidException(org.jaudiotagger.tag.FieldDataInvalidException) FileOutputStream(java.io.FileOutputStream) ReadOnlyFileException(org.jaudiotagger.audio.exceptions.ReadOnlyFileException) Tag(org.jaudiotagger.tag.Tag) AudioFile(org.jaudiotagger.audio.AudioFile) File(java.io.File)

Example 2 with CannotWriteException

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

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

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

the class DownloadReceiver method commitAudio.

private void commitAudio(Context context, AudioFile f, File file) {
    try {
        f.commit();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            Uri contentUri = Uri.fromFile(file);
            mediaScanIntent.setData(contentUri);
            context.sendBroadcast(mediaScanIntent);
        } else {
            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Utils.getStoragePath(context))));
        }
    } catch (CannotWriteException e) {
        e.printStackTrace();
    }
}
Also used : CannotWriteException(org.jaudiotagger.audio.exceptions.CannotWriteException) Intent(android.content.Intent) Uri(android.net.Uri)

Example 5 with CannotWriteException

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

the class AudioFileWriter method write.

/**
 * Write the tag (if not empty) present in the AudioFile in the associated
 * File
 *
 * @param af The file we want to process
 * @throws CannotWriteException if anything went wrong
 */
// TODO Creates temp file in same folder as the original file, this is safe
// but would impose a performance overhead if the original file is on a networked drive
public void write(AudioFile af) throws CannotWriteException {
    logger.config("Started writing tag data for file:" + af.getFile().getName());
    // Prechecks
    precheckWrite(af);
    // mp3's use a different mechanism to the other formats
    if (af instanceof MP3File) {
        af.commit();
        return;
    }
    RandomAccessFile raf = null;
    RandomAccessFile rafTemp = null;
    File newFile;
    File result;
    // Create temporary File
    try {
        newFile = File.createTempFile(af.getFile().getName().replace('.', '_'), TEMP_FILENAME_SUFFIX, af.getFile().getParentFile());
    }// Files/Write Data set to Deny
     catch (IOException ioe) {
        if (ioe.getMessage().equals(FILE_NAME_TOO_LONG) && (af.getFile().getName().length() > FILE_NAME_TOO_LONG_SAFE_LIMIT)) {
            try {
                newFile = File.createTempFile(af.getFile().getName().substring(0, FILE_NAME_TOO_LONG_SAFE_LIMIT).replace('.', '_'), TEMP_FILENAME_SUFFIX, af.getFile().getParentFile());
            } catch (IOException ioe2) {
                logger.log(Level.SEVERE, ErrorMessage.GENERAL_WRITE_FAILED_TO_CREATE_TEMPORARY_FILE_IN_FOLDER.getMsg(af.getFile().getName(), af.getFile().getParentFile().getAbsolutePath()), ioe2);
                throw new CannotWriteException(ErrorMessage.GENERAL_WRITE_FAILED_TO_CREATE_TEMPORARY_FILE_IN_FOLDER.getMsg(af.getFile().getName(), af.getFile().getParentFile().getAbsolutePath()));
            }
        } else {
            logger.log(Level.SEVERE, ErrorMessage.GENERAL_WRITE_FAILED_TO_CREATE_TEMPORARY_FILE_IN_FOLDER.getMsg(af.getFile().getName(), af.getFile().getParentFile().getAbsolutePath()), ioe);
            throw new CannotWriteException(ErrorMessage.GENERAL_WRITE_FAILED_TO_CREATE_TEMPORARY_FILE_IN_FOLDER.getMsg(af.getFile().getName(), af.getFile().getParentFile().getAbsolutePath()));
        }
    }
    // Open temporary file and actual file for editing
    try {
        rafTemp = new RandomAccessFile(newFile, WRITE_MODE);
        raf = new RandomAccessFile(af.getFile(), WRITE_MODE);
    }// Folders/Append Data set to Deny
     catch (IOException ioe) {
        logger.log(Level.SEVERE, ErrorMessage.GENERAL_WRITE_FAILED_TO_OPEN_FILE_FOR_EDITING.getMsg(af.getFile().getAbsolutePath()), ioe);
        // If we managed to open either file, delete it.
        try {
            if (raf != null) {
                raf.close();
            }
            if (rafTemp != null) {
                rafTemp.close();
            }
        } catch (IOException ioe2) {
            // Warn but assume has worked okay
            logger.log(Level.WARNING, ErrorMessage.GENERAL_WRITE_PROBLEM_CLOSING_FILE_HANDLE.getMsg(af.getFile(), ioe.getMessage()), ioe2);
        }
        // rafTemp)
        if (!newFile.delete()) {
            // Non critical failed deletion
            logger.warning(ErrorMessage.GENERAL_WRITE_FAILED_TO_DELETE_TEMPORARY_FILE.getMsg(newFile.getAbsolutePath()));
        }
        throw new CannotWriteException(ErrorMessage.GENERAL_WRITE_FAILED_TO_OPEN_FILE_FOR_EDITING.getMsg(af.getFile().getAbsolutePath()));
    }
    // Write data to File
    try {
        raf.seek(0);
        rafTemp.seek(0);
        try {
            if (this.modificationListener != null) {
                this.modificationListener.fileWillBeModified(af, false);
            }
            writeTag(af.getTag(), raf, rafTemp);
            if (this.modificationListener != null) {
                this.modificationListener.fileModified(af, newFile);
            }
        } catch (ModifyVetoException veto) {
            throw new CannotWriteException(veto);
        }
    } catch (Exception e) {
        logger.log(Level.SEVERE, ErrorMessage.GENERAL_WRITE_FAILED_BECAUSE.getMsg(af.getFile(), e.getMessage()), e);
        try {
            if (raf != null) {
                raf.close();
            }
            if (rafTemp != null) {
                rafTemp.close();
            }
        } catch (IOException ioe) {
            // Warn but assume has worked okay
            logger.log(Level.WARNING, ErrorMessage.GENERAL_WRITE_PROBLEM_CLOSING_FILE_HANDLE.getMsg(af.getFile().getAbsolutePath(), ioe.getMessage()), ioe);
        }
        // file so we can just delete it.
        if (!newFile.delete()) {
            // Non critical failed deletion
            logger.warning(ErrorMessage.GENERAL_WRITE_FAILED_TO_DELETE_TEMPORARY_FILE.getMsg(newFile.getAbsolutePath()));
        }
        throw new CannotWriteException(ErrorMessage.GENERAL_WRITE_FAILED_BECAUSE.getMsg(af.getFile(), e.getMessage()));
    } finally {
        try {
            if (raf != null) {
                raf.close();
            }
            if (rafTemp != null) {
                rafTemp.close();
            }
        } catch (IOException ioe) {
            // Warn but assume has worked okay
            logger.log(Level.WARNING, ErrorMessage.GENERAL_WRITE_PROBLEM_CLOSING_FILE_HANDLE.getMsg(af.getFile().getAbsolutePath(), ioe.getMessage()), ioe);
        }
    }
    // Result held in this file
    result = af.getFile();
    // If the temporary file was used
    if (newFile.length() > 0) {
        // Rename Original File
        // Can fail on Vista if have Special Permission 'Delete' set Deny
        File originalFileBackup = new File(af.getFile().getAbsoluteFile().getParentFile().getPath(), AudioFile.getBaseFilename(af.getFile()) + ".old");
        // If already exists modify the suffix
        int count = 1;
        while (originalFileBackup.exists()) {
            originalFileBackup = new File(af.getFile().getAbsoluteFile().getParentFile().getPath(), AudioFile.getBaseFilename(af.getFile()) + ".old" + count);
            count++;
        }
        boolean renameResult = Utils.rename(af.getFile(), originalFileBackup);
        if (!renameResult) {
            logger.log(Level.SEVERE, ErrorMessage.GENERAL_WRITE_FAILED_TO_RENAME_ORIGINAL_FILE_TO_BACKUP.getMsg(af.getFile().getAbsolutePath(), originalFileBackup.getName()));
            // Delete the temp file because write has failed
            if (newFile != null) {
                newFile.delete();
            }
            throw new CannotWriteException(ErrorMessage.GENERAL_WRITE_FAILED_TO_RENAME_ORIGINAL_FILE_TO_BACKUP.getMsg(af.getFile().getPath(), originalFileBackup.getName()));
        }
        // Rename Temp File to Original File
        renameResult = Utils.rename(newFile, af.getFile());
        if (!renameResult) {
            // New File doesnt exist
            if (!newFile.exists()) {
                logger.warning(ErrorMessage.GENERAL_WRITE_FAILED_NEW_FILE_DOESNT_EXIST.getMsg(newFile.getAbsolutePath()));
            }
            // Rename the backup back to the original
            if (!originalFileBackup.renameTo(af.getFile())) {
                // TODO now if this happens we are left with testfile.old
                // instead of testfile.mp4
                logger.warning(ErrorMessage.GENERAL_WRITE_FAILED_TO_RENAME_ORIGINAL_BACKUP_TO_ORIGINAL.getMsg(originalFileBackup.getAbsolutePath(), af.getFile().getName()));
            }
            logger.warning(ErrorMessage.GENERAL_WRITE_FAILED_TO_RENAME_TO_ORIGINAL_FILE.getMsg(af.getFile().getAbsolutePath(), newFile.getName()));
            throw new CannotWriteException(ErrorMessage.GENERAL_WRITE_FAILED_TO_RENAME_TO_ORIGINAL_FILE.getMsg(af.getFile().getAbsolutePath(), newFile.getName()));
        } else {
            // Rename was okay so we can now delete the backup of the
            // original
            boolean deleteResult = originalFileBackup.delete();
            if (!deleteResult) {
                // Not a disaster but can'timer delete the backup so make a
                // warning
                logger.warning(ErrorMessage.GENERAL_WRITE_WARNING_UNABLE_TO_DELETE_BACKUP_FILE.getMsg(originalFileBackup.getAbsolutePath()));
            }
        }
        // Delete the temporary file if still exists
        if (newFile.exists()) {
            if (!newFile.delete()) {
                // Non critical failed deletion
                logger.warning(ErrorMessage.GENERAL_WRITE_FAILED_TO_DELETE_TEMPORARY_FILE.getMsg(newFile.getPath()));
            }
        }
    } else {
        // Delete the temporary file that wasn'timer ever used
        if (!newFile.delete()) {
            // Non critical failed deletion
            logger.warning(ErrorMessage.GENERAL_WRITE_FAILED_TO_DELETE_TEMPORARY_FILE.getMsg(newFile.getPath()));
        }
    }
    if (this.modificationListener != null) {
        this.modificationListener.fileOperationFinished(result);
    }
}
Also used : CannotWriteException(org.jaudiotagger.audio.exceptions.CannotWriteException) RandomAccessFile(java.io.RandomAccessFile) IOException(java.io.IOException) RandomAccessFile(java.io.RandomAccessFile) AudioFile(org.jaudiotagger.audio.AudioFile) File(java.io.File) MP3File(org.jaudiotagger.audio.mp3.MP3File) ModifyVetoException(org.jaudiotagger.audio.exceptions.ModifyVetoException) CannotReadException(org.jaudiotagger.audio.exceptions.CannotReadException) ModifyVetoException(org.jaudiotagger.audio.exceptions.ModifyVetoException) IOException(java.io.IOException) CannotWriteException(org.jaudiotagger.audio.exceptions.CannotWriteException) MP3File(org.jaudiotagger.audio.mp3.MP3File)

Aggregations

CannotWriteException (org.jaudiotagger.audio.exceptions.CannotWriteException)15 CannotReadException (org.jaudiotagger.audio.exceptions.CannotReadException)12 IOException (java.io.IOException)10 File (java.io.File)9 AudioFile (org.jaudiotagger.audio.AudioFile)9 InvalidAudioFrameException (org.jaudiotagger.audio.exceptions.InvalidAudioFrameException)7 ReadOnlyFileException (org.jaudiotagger.audio.exceptions.ReadOnlyFileException)7 Tag (org.jaudiotagger.tag.Tag)7 TagException (org.jaudiotagger.tag.TagException)6 FileOutputStream (java.io.FileOutputStream)4 ContentValues (android.content.ContentValues)3 Cursor (android.database.Cursor)3 ByteBuffer (java.nio.ByteBuffer)3 FieldDataInvalidException (org.jaudiotagger.tag.FieldDataInvalidException)3 KeyNotFoundException (org.jaudiotagger.tag.KeyNotFoundException)3 Intent (android.content.Intent)2 ParcelFileDescriptor (android.os.ParcelFileDescriptor)2 DocumentFile (android.support.v4.provider.DocumentFile)2 DBAccessHelper (com.jams.music.player.DBHelpers.DBAccessHelper)2 TagUpdate (com.simplecity.amp_library.model.TagUpdate)2