Search in sources :

Example 6 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 7 with CannotReadException

use of org.jaudiotagger.audio.exceptions.CannotReadException in project Shuttle by timusus.

the class LyricsFragment method getLyrics.

public String getLyrics() {
    String lyrics = getActivity().getString(R.string.no_lyrics);
    String filePath = MusicUtils.getFilePath();
    if (filePath == null) {
        return lyrics;
    }
    if (filePath.startsWith("content://")) {
        String path = MusicUtils.getFilePath();
        if (path != null) {
            Query query = new Query.Builder().uri(Uri.parse(path)).projection(new String[] { MediaStore.Audio.Media.DATA }).build();
            Cursor cursor = SqlUtils.createQuery(getContext(), query);
            if (cursor != null) {
                int colIndex = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
                if (cursor.moveToFirst()) {
                    filePath = cursor.getString(colIndex);
                }
                cursor.close();
            }
        }
    }
    File file = new File(filePath);
    if (file.exists()) {
        try {
            AudioFile audioFile = AudioFileIO.read(file);
            if (audioFile != null) {
                Tag tag = audioFile.getTag();
                if (tag != null) {
                    String tagLyrics = tag.getFirst(FieldKey.LYRICS);
                    if (tagLyrics != null && tagLyrics.length() != 0) {
                        lyrics = tagLyrics.replace("\r", "\n");
                    }
                }
            }
        } catch (CannotReadException | IOException | TagException | ReadOnlyFileException | InvalidAudioFrameException | UnsupportedOperationException ignored) {
        }
    }
    return lyrics;
}
Also used : Query(com.simplecity.amp_library.model.Query) CannotReadException(org.jaudiotagger.audio.exceptions.CannotReadException) InvalidAudioFrameException(org.jaudiotagger.audio.exceptions.InvalidAudioFrameException) IOException(java.io.IOException) Cursor(android.database.Cursor) AudioFile(org.jaudiotagger.audio.AudioFile) TagException(org.jaudiotagger.tag.TagException) ReadOnlyFileException(org.jaudiotagger.audio.exceptions.ReadOnlyFileException) Tag(org.jaudiotagger.tag.Tag) AudioFile(org.jaudiotagger.audio.AudioFile) File(java.io.File)

Example 8 with CannotReadException

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

the class EditLocalSongFragment method onResume.

@Override
public void onResume() {
    super.onResume();
    mp3File = null;
    try {
        File f = new File(HomeActivity.editSong.getPath());
        mp3File = (MP3File) AudioFileIO.read(f);
    } catch (IOException | CannotReadException | InvalidAudioFrameException | TagException | ReadOnlyFileException e) {
        e.printStackTrace();
    } catch (ClassCastException e) {
        mp3File = null;
        e.printStackTrace();
    }
    if (mp3File == null) {
        Toast.makeText(ctx, "Error in loading the file", Toast.LENGTH_SHORT).show();
        mCallback.onEditSongSave(false);
    }
    if (mp3File != null && !mp3File.hasID3v2Tag()) {
        Toast.makeText(ctx, "No Tags Found", Toast.LENGTH_SHORT).show();
        mCallback.onEditSongSave(false);
    }
    if (mp3File != null && mp3File.hasID3v2Tag()) {
        titleText.setText(HomeActivity.editSong.getTitle());
        artistText.setText(HomeActivity.editSong.getArtist());
        albumText.setText(HomeActivity.editSong.getAlbum());
    }
    try {
        tag = mp3File.getTag();
        id3v1Tag = mp3File.getID3v1Tag();
        id3v2Tag = mp3File.getID3v2Tag();
        id3v24Tag = mp3File.getID3v2TagAsv24();
    } catch (Exception e) {
        e.printStackTrace();
        Toast.makeText(ctx, "Error in finding tags", Toast.LENGTH_SHORT).show();
        mCallback.onEditSongSave(false);
    }
}
Also used : CannotReadException(org.jaudiotagger.audio.exceptions.CannotReadException) TagException(org.jaudiotagger.tag.TagException) InvalidAudioFrameException(org.jaudiotagger.audio.exceptions.InvalidAudioFrameException) ReadOnlyFileException(org.jaudiotagger.audio.exceptions.ReadOnlyFileException) IOException(java.io.IOException) MP3File(org.jaudiotagger.audio.mp3.MP3File) File(java.io.File) ReadOnlyFileException(org.jaudiotagger.audio.exceptions.ReadOnlyFileException) CannotReadException(org.jaudiotagger.audio.exceptions.CannotReadException) FieldDataInvalidException(org.jaudiotagger.tag.FieldDataInvalidException) CannotWriteException(org.jaudiotagger.audio.exceptions.CannotWriteException) IOException(java.io.IOException) TagException(org.jaudiotagger.tag.TagException) InvalidAudioFrameException(org.jaudiotagger.audio.exceptions.InvalidAudioFrameException)

Example 9 with CannotReadException

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

the class OggInfoReader method read.

public GenericAudioHeader read(RandomAccessFile raf) throws CannotReadException, IOException {
    long start = raf.getFilePointer();
    GenericAudioHeader info = new GenericAudioHeader();
    logger.fine("Started");
    long oldPos;
    //Check start of file does it have Ogg pattern
    byte[] b = new byte[OggPageHeader.CAPTURE_PATTERN.length];
    raf.read(b);
    if (!(Arrays.equals(b, OggPageHeader.CAPTURE_PATTERN))) {
        raf.seek(0);
        if (AbstractID3v2Tag.isId3Tag(raf)) {
            raf.read(b);
            if ((Arrays.equals(b, OggPageHeader.CAPTURE_PATTERN))) {
                start = raf.getFilePointer();
            }
        } else {
            throw new CannotReadException(ErrorMessage.OGG_HEADER_CANNOT_BE_FOUND.getMsg(new String(b)));
        }
    }
    //Now work backwards from file looking for the last ogg page, it reads the granule position for this last page
    //which must be set.
    //TODO should do buffering to cut down the number of file reads
    raf.seek(start);
    double pcmSamplesNumber = -1;
    raf.seek(raf.length() - 2);
    while (raf.getFilePointer() >= 4) {
        if (raf.read() == OggPageHeader.CAPTURE_PATTERN[3]) {
            raf.seek(raf.getFilePointer() - OggPageHeader.FIELD_CAPTURE_PATTERN_LENGTH);
            byte[] ogg = new byte[3];
            raf.readFully(ogg);
            if (ogg[0] == OggPageHeader.CAPTURE_PATTERN[0] && ogg[1] == OggPageHeader.CAPTURE_PATTERN[1] && ogg[2] == OggPageHeader.CAPTURE_PATTERN[2]) {
                raf.seek(raf.getFilePointer() - 3);
                oldPos = raf.getFilePointer();
                raf.seek(raf.getFilePointer() + OggPageHeader.FIELD_PAGE_SEGMENTS_POS);
                //Unsigned
                int pageSegments = raf.readByte() & 0xFF;
                raf.seek(oldPos);
                b = new byte[OggPageHeader.OGG_PAGE_HEADER_FIXED_LENGTH + pageSegments];
                raf.readFully(b);
                OggPageHeader pageHeader = new OggPageHeader(b);
                raf.seek(0);
                pcmSamplesNumber = pageHeader.getAbsoluteGranulePosition();
                break;
            }
        }
        raf.seek(raf.getFilePointer() - 2);
    }
    if (pcmSamplesNumber == -1) {
        //According to spec a value of -1 indicates no packet finished on this page, this should not occur
        throw new CannotReadException(ErrorMessage.OGG_VORBIS_NO_SETUP_BLOCK.getMsg());
    }
    //1st page = Identification Header
    OggPageHeader pageHeader = OggPageHeader.read(raf);
    byte[] vorbisData = new byte[pageHeader.getPageLength()];
    raf.read(vorbisData);
    VorbisIdentificationHeader vorbisIdentificationHeader = new VorbisIdentificationHeader(vorbisData);
    //Map to generic encodingInfo
    info.setPreciseLength((float) (pcmSamplesNumber / vorbisIdentificationHeader.getSamplingRate()));
    info.setChannelNumber(vorbisIdentificationHeader.getChannelNumber());
    info.setSamplingRate(vorbisIdentificationHeader.getSamplingRate());
    info.setEncodingType(vorbisIdentificationHeader.getEncodingType());
    info.setExtraEncodingInfos("");
    //According to Wikipedia Vorbis Page, Vorbis only works on 16bits 44khz 
    info.setBitsPerSample(16);
    //TODO this calculation should be done within identification header
    if (vorbisIdentificationHeader.getNominalBitrate() != 0 && vorbisIdentificationHeader.getMaxBitrate() == vorbisIdentificationHeader.getNominalBitrate() && vorbisIdentificationHeader.getMinBitrate() == vorbisIdentificationHeader.getNominalBitrate()) {
        //CBR (in kbps)
        info.setBitrate(vorbisIdentificationHeader.getNominalBitrate() / 1000);
        info.setVariableBitRate(false);
    } else if (vorbisIdentificationHeader.getNominalBitrate() != 0 && vorbisIdentificationHeader.getMaxBitrate() == 0 && vorbisIdentificationHeader.getMinBitrate() == 0) {
        //Average vbr (in kpbs)
        info.setBitrate(vorbisIdentificationHeader.getNominalBitrate() / 1000);
        info.setVariableBitRate(true);
    } else {
        //TODO need to remove comment from raf.getLength()
        info.setBitrate(computeBitrate(info.getTrackLength(), raf.length()));
        info.setVariableBitRate(true);
    }
    logger.fine("Finished");
    return info;
}
Also used : CannotReadException(org.jaudiotagger.audio.exceptions.CannotReadException) GenericAudioHeader(org.jaudiotagger.audio.generic.GenericAudioHeader)

Example 10 with CannotReadException

use of org.jaudiotagger.audio.exceptions.CannotReadException in project musiccabinet by hakko.

the class AudioTagService method updateMetadata.

public void updateMetadata(File file) {
    String extension = getExtension(file.getFilename()).toUpperCase();
    if (!ALLOWED_EXTENSIONS.contains(extension)) {
        return;
    }
    MetaData metaData = new MetaData();
    metaData.setMediaType(Mediatype.valueOf(extension));
    try {
        AudioFile audioFile = AudioFileIO.read(new java.io.File(file.getDirectory(), file.getFilename()));
        Tag tag = audioFile.getTag();
        if (tag != null) {
            metaData.setArtist(getTagField(tag, ARTIST));
            metaData.setArtistSort(getTagField(tag, ARTIST_SORT));
            metaData.setAlbumArtist(toAlbumArtist(tag));
            metaData.setAlbumArtistSort(getTagField(tag, ALBUM_ARTIST_SORT));
            metaData.setAlbum(toAlbum(getTagField(tag, ALBUM)));
            metaData.setTitle(getTagField(tag, TITLE));
            metaData.setYear(getTagField(tag, YEAR));
            metaData.setGenre(toGenre(getTagField(tag, GENRE)));
            metaData.setLyrics(getTagField(tag, LYRICS));
            metaData.setComposer(getTagField(tag, COMPOSER));
            metaData.setDiscNr(toFirstNumber(getTagField(tag, DISC_NO)));
            metaData.setDiscNrs(toShort(getTagField(tag, DISC_TOTAL)));
            metaData.setTrackNr(toFirstNumber(getTagField(tag, TRACK)));
            metaData.setTrackNrs(toShort(getTagField(tag, TRACK_TOTAL)));
            metaData.setCoverArtEmbedded(tag.getFirstArtwork() != null);
        }
        AudioHeader audioHeader = audioFile.getAudioHeader();
        if (audioHeader != null) {
            metaData.setVbr(audioHeader.isVariableBitRate());
            metaData.setBitrate((short) audioHeader.getBitRateAsNumber());
            metaData.setDuration((short) audioHeader.getTrackLength());
        }
        file.setMetaData(metaData);
    } catch (CannotReadException | IOException | TagException | ReadOnlyFileException | InvalidAudioFrameException | RuntimeException e) {
        // AudioFileIO has been seen to throw NumberFormatException
        LOG.warn("Could not read metadata of file " + file.getFilename() + " from " + file.getDirectory(), e);
    }
}
Also used : AudioHeader(org.jaudiotagger.audio.AudioHeader) CannotReadException(org.jaudiotagger.audio.exceptions.CannotReadException) InvalidAudioFrameException(org.jaudiotagger.audio.exceptions.InvalidAudioFrameException) IOException(java.io.IOException) AudioFile(org.jaudiotagger.audio.AudioFile) TagException(org.jaudiotagger.tag.TagException) MetaData(com.github.hakko.musiccabinet.domain.model.library.MetaData) ReadOnlyFileException(org.jaudiotagger.audio.exceptions.ReadOnlyFileException) FlacTag(org.jaudiotagger.tag.flac.FlacTag) Tag(org.jaudiotagger.tag.Tag) AbstractID3v2Tag(org.jaudiotagger.tag.id3.AbstractID3v2Tag)

Aggregations

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