Java Code Examples for org.jaudiotagger.audio.AudioFile

The following examples show how to use org.jaudiotagger.audio.AudioFile. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: subsonic   Source File: JaudiotaggerParser.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Parses meta data for the given music file. No guessing or reformatting is done.
 *
 *
 * @param file The music file to parse.
 * @return Meta data for the file.
 */
@Override
public MetaData getRawMetaData(File file) {

    MetaData metaData = new MetaData();

    try {
        AudioFile audioFile = AudioFileIO.read(file);
        Tag tag = audioFile.getTag();
        if (tag != null) {
            metaData.setAlbumName(getTagField(tag, FieldKey.ALBUM));
            metaData.setTitle(getTagField(tag, FieldKey.TITLE));
            metaData.setYear(parseYear(getTagField(tag, FieldKey.YEAR)));
            metaData.setGenre(mapGenre(getTagField(tag, FieldKey.GENRE)));
            metaData.setDiscNumber(parseInteger(getTagField(tag, FieldKey.DISC_NO)));
            metaData.setTrackNumber(parseTrackNumber(getTagField(tag, FieldKey.TRACK)));

            String songArtist = getTagField(tag, FieldKey.ARTIST);
            String albumArtist = getTagField(tag, FieldKey.ALBUM_ARTIST);
            metaData.setArtist(StringUtils.isBlank(songArtist) ? albumArtist : songArtist);
            metaData.setAlbumArtist(StringUtils.isBlank(albumArtist) ? songArtist : albumArtist);
        }

        AudioHeader audioHeader = audioFile.getAudioHeader();
        if (audioHeader != null) {
            metaData.setVariableBitRate(audioHeader.isVariableBitRate());
            metaData.setBitRate((int) audioHeader.getBitRateAsNumber());
            metaData.setDurationSeconds(audioHeader.getTrackLength());
        }


    } catch (Throwable x) {
        LOG.warn("Error when parsing tags in " + file, x);
    }

    return metaData;
}
 
Example 2
Source Project: MusicPlayer   Source File: Album.java    License: MIT License 6 votes vote down vote up
public Image getArtwork() {
    if (this.artwork == null) {

        try {
            String location = this.songs.get(0).getLocation();
            AudioFile audioFile = AudioFileIO.read(new File(location));
            Tag tag = audioFile.getTag();
            byte[] bytes = tag.getFirstArtwork().getBinaryData();
            ByteArrayInputStream in = new ByteArrayInputStream(bytes);
            this.artwork = new Image(in, 300, 300, true, true);

            if (this.artwork.isError()) {
                this.artwork = new Image(Resources.IMG + "albumsIcon.png");
            }

        } catch (Exception ex) {
            this.artwork = new Image(Resources.IMG + "albumsIcon.png");
        }
    }
    return this.artwork;
}
 
Example 3
Source Project: QuickLyric   Source File: Id3Writer.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
protected Boolean doInBackground(Object... params) {
    Lyrics editedLyrics = (Lyrics) params[0];
    File musicFile = (File) params[1];
    boolean failed = false;

    if (musicFile != null)
        try {
            AudioFile af = AudioFileIO.read(musicFile);
            TagOptionSingleton.getInstance().setAndroid(true);
            Tag tags = af.getTag();
            tags.setField(FieldKey.ARTIST, editedLyrics.getArtist());
            tags.setField(FieldKey.TITLE, editedLyrics.getTitle());
            tags.setField(FieldKey.LYRICS, Html.fromHtml(editedLyrics.getText()).toString());
            af.setTag(tags);
            AudioFileIO.write(af);
        } catch (CannotReadException | IOException | ReadOnlyFileException | TagException
                | InvalidAudioFrameException | NullPointerException | CannotWriteException e) {
            e.printStackTrace();
            failed = true;
        }
    return failed;
}
 
Example 4
Source Project: QuickLyric   Source File: Id3Reader.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static Lyrics getLyrics(Context context, String artist, String title, boolean requestPermission) {
    String text = null;
    try {
        for (File file : getFiles(context, artist, title, requestPermission)) {
            AudioFile af = AudioFileIO.read(file);
            TagOptionSingleton.getInstance().setAndroid(true);
            Tag tag = af.getTag();
            text = tag.getFirst(FieldKey.LYRICS);
            if (!text.isEmpty()) {
                text = text.replaceAll("\n", "<br/>");
                break;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
    if (TextUtils.isEmpty(text))
        return null;
    Lyrics lyrics = new Lyrics(POSITIVE_RESULT);
    lyrics.setArtist(artist);
    lyrics.setTitle(title);
    lyrics.setText(text);
    lyrics.setSource("Storage");
    return lyrics;
}
 
Example 5
Source Project: HubPlayer   Source File: BasicPlayer.java    License: GNU General Public License v3.0 6 votes vote down vote up
public int getAudioTrackLength(URL url) {
	try {

		// 只能获得本地歌曲文件的信息
		AudioFile file = AudioFileIO.read(new File(url.toURI()));

		// 获取音频文件的头信息
		AudioHeader audioHeader = file.getAudioHeader();
		// 文件长度 转换成时间
		return audioHeader.getTrackLength();
	} catch (CannotReadException | IOException | TagException
			| ReadOnlyFileException | InvalidAudioFrameException
			| URISyntaxException e) {
		e.printStackTrace();
		return -1;
	}

}
 
Example 6
@NonNull
private AudioFile getAudioFile(@NonNull String path) {
    try {
        return AudioFileIO.read(new File(path));
    } catch (Exception e) {
        Log.e(TAG, "Could not read audio file " + path, e);
        return new AudioFile();
    }
}
 
Example 7
Source Project: Orin   Source File: AbsTagEditorActivity.java    License: GNU General Public License v3.0 5 votes vote down vote up
@NonNull
private AudioFile getAudioFile(@NonNull String path) {
    try {
        return AudioFileIO.read(new File(path));
    } catch (Exception e) {
        Log.e(TAG, "Could not read audio file " + path, e);
        return new AudioFile();
    }
}
 
Example 8
Source Project: airsonic   Source File: JaudiotaggerParser.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static Artwork getArtwork(MediaFile file) {
    AudioFile audioFile;
    try {
        audioFile = AudioFileIO.read(file.getFile());
    } catch (Throwable e) {
        LOG.warn("Failed to find cover art tag in " + file, e);
        return null;
    }
    Tag tag = audioFile.getTag();
    return tag == null ? null : tag.getFirstArtwork();
}
 
Example 9
Source Project: Rey-MusicPlayer   Source File: AlbumsArtDownloadService.java    License: Apache License 2.0 5 votes vote down vote up
public void setAlbumArt(File file, Bitmap artworkBitmap, Song song) throws IOException, TagException, ReadOnlyFileException, CannotReadException, InvalidAudioFrameException {

        artworkBitmap = Bitmap.createScaledBitmap(artworkBitmap, 500, 500, false);

        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        artworkBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);

        byte[] byteArray = stream.toByteArray();

        File artworkFile = new File(Environment.getExternalStorageDirectory() + "/artwork.jpg");

        if (!artworkFile.exists())
            artworkFile.createNewFile();

        FileOutputStream out = new FileOutputStream(artworkFile);
        artworkBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);

        Artwork artwork = Artwork.createArtworkFromFile(artworkFile);

        artwork.setBinaryData(byteArray);
        AudioFile audioFile = AudioFileIO.read(file);
        Tag tag = audioFile.getTagOrCreateAndSetDefault();


        if (tag.getFirstArtwork() != null) {
            tag.deleteArtworkField();
            tag.setField(artwork);
        } else {
            tag.addField(artwork);
        }

        Uri uri = MusicUtils.getAlbumArtUri(song._albumId);
        DiskCacheUtils.removeFromCache(uri.toString(), ImageLoader.getInstance().getDiskCache());
        String path = FileUtils.getRealPathFromURI(uri);
        new File(path).delete();
        artworkFile.delete();
    }
 
Example 10
@NonNull
private AudioFile getAudioFile(@NonNull String path) {
    try {
        return AudioFileIO.read(new File(path));
    } catch (Exception e) {
        Log.e(TAG, "Could not read audio file " + path, e);
        return new AudioFile();
    }
}
 
Example 11
public static void setReplayGainValues(Song song) {
  float rgTrack = 0.0f;
  float rgAlbum = 0.0f;

  Map<String, Float> tags = null;

  try {
    AudioFile file = AudioFileIO.read(new File(song.data));
    Tag tag = file.getTag();

    if (tag instanceof VorbisCommentTag) {
      tags = parseVorbisTags((VorbisCommentTag) tag);
    } else if (tag instanceof FlacTag) {
      tags = parseVorbisTags(((FlacTag) tag).getVorbisCommentTag());
    } else {
      tags = parseId3Tags(tag, song.data);
    }
  } catch (Exception e) {
    e.printStackTrace();
  }

  if (tags != null && !tags.isEmpty()) {
    if (tags.containsKey(REPLAYGAIN_TRACK_GAIN)) {
      rgTrack = tags.get(REPLAYGAIN_TRACK_GAIN);
    }
    if (tags.containsKey(REPLAYGAIN_ALBUM_GAIN)) {
      rgAlbum = tags.get(REPLAYGAIN_ALBUM_GAIN);
    }
  }
  song.setReplayGainValues(rgTrack, rgAlbum);
}
 
Example 12
@NonNull
private AudioFile getAudioFile(@NonNull String path) {
    try {
        return AudioFileIO.read(new File(path));
    } catch (Exception e) {
        Log.e(TAG, "Could not read audio file " + path, e);
        return new AudioFile();
    }
}
 
Example 13
Source Project: VinylMusicPlayer   Source File: SAFUtil.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static void write(Context context, AudioFile audio, Uri safUri) {
    if (isSAFRequired(audio)) {
        writeSAF(context, audio, safUri);
    } else {
        try {
            writeFile(audio);
        } catch (CannotWriteException e) {
            e.printStackTrace();
        }
    }
}
 
Example 14
Source Project: APlayer   Source File: MediaStoreUtil.java    License: GNU General Public License v3.0 5 votes vote down vote up
@WorkerThread
public static void saveArtwork(Context context, int albumId, File artFile)
    throws TagException, ReadOnlyFileException, CannotReadException, InvalidAudioFrameException, IOException, CannotWriteException {
  Song song = MediaStoreUtil.getSongByAlbumId(albumId);
  if (song == null) {
    return;
  }
  AudioFile audioFile = AudioFileIO.read(new File(song.getUrl()));
  Tag tag = audioFile.getTagOrCreateAndSetDefault();
  Artwork artwork = ArtworkFactory.createArtworkFromFile(artFile);
  tag.deleteArtworkField();
  tag.setField(artwork);
  audioFile.commit();
  insertAlbumArt(context, albumId, artFile.getAbsolutePath());
}
 
Example 15
@NonNull
private AudioFile getAudioFile(@NonNull String path) {
    try {
        return AudioFileIO.read(new File(path));
    } catch (Exception e) {
        Log.e(TAG, "Could not read audio file " + path, e);
        return new AudioFile();
    }
}
 
Example 16
Source Project: QuickLyric   Source File: Id3Reader.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static Bitmap getCover(Context context, String artist, String title, boolean requestPermission) {
    try {
        Tag tag = null;
        for (File file : getFiles(context, artist, title, requestPermission)) {
            AudioFile af = AudioFileIO.read(file);
            TagOptionSingleton.getInstance().setAndroid(true);
            tag = af.getTag();
            if (!tag.getArtworkList().isEmpty())
                break;
        }
        if (tag.getFirstArtwork() == null)
            return null;
        byte[] byteArray = tag.getFirstArtwork().getBinaryData();
        ByteArrayInputStream imageStream = new ByteArrayInputStream(byteArray);

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(imageStream, null, options);

        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);

        options.inJustDecodeBounds = false;
        options.inSampleSize = options.outWidth / size.x;

        return BitmapFactory.decodeStream(imageStream, null, options);
    } catch (Exception e) {
        return null;
    }
}
 
Example 17
/**
 * Parses meta data for the given music file. No guessing or reformatting is done.
 *
 *
 * @param file The music file to parse.
 * @return Meta data for the file.
 */
@Override
public MetaData getRawMetaData(Path file) {

    MetaData metaData = new MetaData();

    try {
        AudioFile audioFile = AudioFileIO.read(file.toFile());
        Tag tag = audioFile.getTag();
        if (tag != null) {
            metaData.setAlbumName(getTagField(tag, FieldKey.ALBUM));
            metaData.setTitle(getTagField(tag, FieldKey.TITLE));
            metaData.setYear(parseIntegerPattern(getTagField(tag, FieldKey.YEAR), YEAR_NUMBER_PATTERN));
            metaData.setGenre(mapGenre(getTagField(tag, FieldKey.GENRE)));
            metaData.setDiscNumber(parseIntegerPattern(getTagField(tag, FieldKey.DISC_NO), null));
            metaData.setTrackNumber(parseIntegerPattern(getTagField(tag, FieldKey.TRACK), TRACK_NUMBER_PATTERN));
            metaData.setMusicBrainzReleaseId(getTagField(tag, FieldKey.MUSICBRAINZ_RELEASEID));
            metaData.setMusicBrainzRecordingId(getTagField(tag, FieldKey.MUSICBRAINZ_TRACK_ID));

            metaData.setArtist(getTagField(tag, FieldKey.ARTIST));
            metaData.setAlbumArtist(getTagField(tag, FieldKey.ALBUM_ARTIST));

            if (StringUtils.isBlank(metaData.getArtist())) {
                metaData.setArtist(metaData.getAlbumArtist());
            }
            if (StringUtils.isBlank(metaData.getAlbumArtist())) {
                metaData.setAlbumArtist(metaData.getArtist());
            }

        }

        AudioHeader audioHeader = audioFile.getAudioHeader();
        if (audioHeader != null) {
            metaData.setVariableBitRate(audioHeader.isVariableBitRate());
            metaData.setBitRate((int) audioHeader.getBitRateAsNumber());
            metaData.setDuration(audioHeader.getPreciseTrackLength());
        }


    } catch (Throwable x) {
        LOG.warn("Error when parsing tags in " + file, x);
    }

    return metaData;
}
 
Example 18
public Artwork getArtwork(MediaFile file) throws Exception {
    AudioFile audioFile = AudioFileIO.read(file.getFile().toFile());
    Tag tag = audioFile.getTag();
    return tag == null ? null : tag.getFirstArtwork();
}
 
Example 19
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    final Activity context = getActivity();
    final Song song = getArguments().getParcelable("song");

    MaterialDialog dialog = new MaterialDialog.Builder(context)
            .customView(R.layout.dialog_file_details, true)
            .title(context.getResources().getString(R.string.label_details))
            .positiveText(android.R.string.ok)
            .build();

    View dialogView = dialog.getCustomView();
    final TextView fileName = dialogView.findViewById(R.id.file_name);
    final TextView filePath = dialogView.findViewById(R.id.file_path);
    final TextView fileSize = dialogView.findViewById(R.id.file_size);
    final TextView fileFormat = dialogView.findViewById(R.id.file_format);
    final TextView songLength = dialogView.findViewById(R.id.song_length);
    final TextView bitRate = dialogView.findViewById(R.id.bitrate);
    final TextView samplingRate = dialogView.findViewById(R.id.sampling_rate);

    fileName.setText(makeTextWithTitle(context, R.string.label_file_name, "-"));
    filePath.setText(makeTextWithTitle(context, R.string.label_file_path, "-"));
    fileSize.setText(makeTextWithTitle(context, R.string.label_file_size, "-"));
    fileFormat.setText(makeTextWithTitle(context, R.string.label_file_format, "-"));
    songLength.setText(makeTextWithTitle(context, R.string.label_song_length, "-"));
    bitRate.setText(makeTextWithTitle(context, R.string.label_bit_rate, "-"));
    samplingRate.setText(makeTextWithTitle(context, R.string.label_sampling_rate, "-"));

    if (song != null) {
        final File songFile = new File(song.data);
        if (songFile.exists()) {
            fileName.setText(makeTextWithTitle(context, R.string.label_file_name, songFile.getName()));
            filePath.setText(makeTextWithTitle(context, R.string.label_file_path, songFile.getAbsolutePath()));
            fileSize.setText(makeTextWithTitle(context, R.string.label_file_size, getFileSizeString(songFile.length())));
            try {
                AudioFile audioFile = AudioFileIO.read(songFile);
                AudioHeader audioHeader = audioFile.getAudioHeader();

                fileFormat.setText(makeTextWithTitle(context, R.string.label_file_format, audioHeader.getFormat()));
                songLength.setText(makeTextWithTitle(context, R.string.label_song_length, MusicUtil.getReadableDurationString(audioHeader.getTrackLength() * 1000)));
                bitRate.setText(makeTextWithTitle(context, R.string.label_bit_rate, audioHeader.getBitRate() + " kb/s"));
                samplingRate.setText(makeTextWithTitle(context, R.string.label_sampling_rate, audioHeader.getSampleRate() + " Hz"));
            } catch (@NonNull CannotReadException | IOException | TagException | ReadOnlyFileException | InvalidAudioFrameException e) {
                Log.e(TAG, "error while reading the song file", e);
                // fallback
                songLength.setText(makeTextWithTitle(context, R.string.label_song_length, MusicUtil.getReadableDurationString(song.duration)));
            }
        } else {
            // fallback
            fileName.setText(makeTextWithTitle(context, R.string.label_file_name, song.title));
            songLength.setText(makeTextWithTitle(context, R.string.label_song_length, MusicUtil.getReadableDurationString(song.duration)));
        }
    }

    return dialog;
}
 
Example 20
@Override
public void onReceive(final Context context, Intent intent) {
    XposedBridge.log("[SoundCloud Downloader] Entering album art downloader...");
    context.unregisterReceiver(this);

    XposedBridge.log("[SoundCloud Downloader] Unregistered receiver, starting Picasso...");
    Picasso.with(XposedMod.currentActivity).setLoggingEnabled(true); // enable logging to see why picasso fails to load
    Picasso.with(XposedMod.currentActivity).load(downloadPayload.getImageUrl()).into(new Target() {
        @Override
        public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
            try {
                File downloadedFile = new File(downloadPayload.getSaveDirectory(), downloadPayload.getFileName());
                if (!downloadedFile.exists()) {
                    XposedBridge.log("[SoundCloud Downloader] downloaded file does not exist, exiting...");
                    return;
                }

                TagOptionSingleton.getInstance().setAndroid(true);
                AudioFile audioFile = AudioFileIO.read(downloadedFile);
                Tag tag = audioFile.getTagOrCreateAndSetDefault();
                tag.setField(FieldKey.ARTIST,downloadPayload.getArtistName());
                tag.setField(FieldKey.GENRE, downloadPayload.getGenre());
                tag.setField(FieldKey.TITLE, downloadPayload.getTitle());
                tag.setField(FieldKey.ALBUM, downloadPayload.getTitle());

                ByteArrayOutputStream imgStream = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 90, imgStream);
                File artworkFile = File.createTempFile(downloadPayload.getTitle(), ".jpg");
                FileOutputStream artworkFileStream = new FileOutputStream(artworkFile);
                artworkFileStream.write(imgStream.toByteArray());
                artworkFileStream.close();
                artworkFile.deleteOnExit();
                imgStream.close();

                Artwork artwork = ArtworkFactory.createArtworkFromFile(artworkFile);
                artwork.setPictureType(3);
                tag.deleteArtworkField();
                tag.addField(artwork);
                tag.setField(artwork);

                audioFile.setTag(tag);
                AudioFileIO.write(audioFile);

                XposedBridge.log("[SoundCloud Downloader] Finished writing metadata...");

                XposedMod.currentActivity.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(audioFile.getFile())));

                XposedBridge.log("[SoundCloud Downloader] Broadcasting update to media scanner...");

            } catch (Exception e) {
                XposedBridge.log("[SoundCloud Downloader] Metadata error: " + e.getMessage());
            }
        }

        @Override
        public void onBitmapFailed(Drawable errorDrawable) {
            XposedBridge.log("[SoundCloud Downloader] Album art fetch failed!");
        }

        @Override
        public void onPrepareLoad(Drawable placeHolderDrawable) {
            XposedBridge.log("[SoundCloud Downloader] Preparing to load picasso...");
        }
    });
}
 
Example 21
Source Project: Orin   Source File: SongDetailDialog.java    License: GNU General Public License v3.0 4 votes vote down vote up
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    final Activity context = getActivity();
    final Song song = getArguments().getParcelable("song");

    MaterialDialog dialog = new MaterialDialog.Builder(context)
            .customView(R.layout.dialog_file_details, true)
            .title(context.getResources().getString(R.string.label_details))
            .positiveText(android.R.string.ok)
            .build();

    View dialogView = dialog.getCustomView();
    final TextView fileName = (TextView) dialogView.findViewById(R.id.file_name);
    final TextView filePath = (TextView) dialogView.findViewById(R.id.file_path);
    final TextView fileSize = (TextView) dialogView.findViewById(R.id.file_size);
    final TextView fileFormat = (TextView) dialogView.findViewById(R.id.file_format);
    final TextView trackLength = (TextView) dialogView.findViewById(R.id.track_length);
    final TextView bitRate = (TextView) dialogView.findViewById(R.id.bitrate);
    final TextView samplingRate = (TextView) dialogView.findViewById(R.id.sampling_rate);

    fileName.setText(makeTextWithTitle(context, R.string.label_file_name, "-"));
    filePath.setText(makeTextWithTitle(context, R.string.label_file_path, "-"));
    fileSize.setText(makeTextWithTitle(context, R.string.label_file_size, "-"));
    fileFormat.setText(makeTextWithTitle(context, R.string.label_file_format, "-"));
    trackLength.setText(makeTextWithTitle(context, R.string.label_track_length, "-"));
    bitRate.setText(makeTextWithTitle(context, R.string.label_bit_rate, "-"));
    samplingRate.setText(makeTextWithTitle(context, R.string.label_sampling_rate, "-"));

    try {
        if (song != null) {
            final File songFile = new File(song.data);
            if (songFile.exists()) {
                AudioFile audioFile = AudioFileIO.read(songFile);
                AudioHeader audioHeader = audioFile.getAudioHeader();

                fileName.setText(makeTextWithTitle(context, R.string.label_file_name, songFile.getName()));
                filePath.setText(makeTextWithTitle(context, R.string.label_file_path, songFile.getAbsolutePath()));
                fileSize.setText(makeTextWithTitle(context, R.string.label_file_size, getFileSizeString(songFile.length())));
                fileFormat.setText(makeTextWithTitle(context, R.string.label_file_format, audioHeader.getFormat()));
                trackLength.setText(makeTextWithTitle(context, R.string.label_track_length, MusicUtil.getReadableDurationString(audioHeader.getTrackLength() * 1000)));
                bitRate.setText(makeTextWithTitle(context, R.string.label_bit_rate, audioHeader.getBitRate() + " kb/s"));
                samplingRate.setText(makeTextWithTitle(context, R.string.label_sampling_rate, audioHeader.getSampleRate() + " Hz"));
            }
        }
    } catch (@NonNull CannotReadException | IOException | TagException | ReadOnlyFileException | InvalidAudioFrameException e) {
        Log.e(TAG, "error while reading the song file", e);
    }
    return dialog;
}
 
Example 22
Source Project: airsonic   Source File: JaudiotaggerParser.java    License: GNU General Public License v3.0 4 votes vote down vote up
/**
 * Parses meta data for the given music file. No guessing or reformatting is done.
 *
 * @param file The music file to parse.
 * @return Meta data for the file.
 */
@Override
public MetaData getRawMetaData(File file) {

    MetaData metaData = new MetaData();

    try {
        AudioFile audioFile = AudioFileIO.read(file);
        Tag tag = audioFile.getTag();
        if (tag != null) {
            metaData.setAlbumArtist(getTagField(tag, FieldKey.ALBUM_ARTIST));
            metaData.setAlbumName(getTagField(tag, FieldKey.ALBUM));
            metaData.setArtist(getTagField(tag, FieldKey.ARTIST));
            metaData.setDiscNumber(parseInteger(getTagField(tag, FieldKey.DISC_NO)));
            metaData.setGenre(mapGenre(getTagField(tag, FieldKey.GENRE)));
            metaData.setMusicBrainzRecordingId(getTagField(tag, FieldKey.MUSICBRAINZ_TRACK_ID));
            metaData.setMusicBrainzReleaseId(getTagField(tag, FieldKey.MUSICBRAINZ_RELEASEID));
            metaData.setTitle(getTagField(tag, FieldKey.TITLE));
            metaData.setTrackNumber(parseIntegerPattern(getTagField(tag, FieldKey.TRACK), TRACK_NUMBER_PATTERN));
            metaData.setYear(parseIntegerPattern(getTagField(tag, FieldKey.YEAR), YEAR_NUMBER_PATTERN));

            if (StringUtils.isBlank(metaData.getArtist())) {
                metaData.setArtist(metaData.getAlbumArtist());
            }
            if (StringUtils.isBlank(metaData.getAlbumArtist())) {
                metaData.setAlbumArtist(metaData.getArtist());
            }

        }

        AudioHeader audioHeader = audioFile.getAudioHeader();
        if (audioHeader != null) {
            metaData.setVariableBitRate(audioHeader.isVariableBitRate());
            metaData.setBitRate((int) audioHeader.getBitRateAsNumber());
            metaData.setDurationSeconds(audioHeader.getTrackLength());
        }


    } catch (Throwable x) {
        LOG.warn("Error when parsing tags in " + file, x);
    }

    return metaData;
}
 
Example 23
Source Project: Rey-MusicPlayer   Source File: Id3TagEditorActivity.java    License: Apache License 2.0 4 votes vote down vote up
private void fetchDetails() {
        File file = new File(SONG_PATH);

        try {
            AudioFile audioFile = AudioFileIO.read(file);
            Tag tag = audioFile.getTagOrCreateAndSetDefault();

            title = tag.getFirst(FieldKey.TITLE);

            mTitleEditText.setText(title);
            mTitleEditText.setSelection(title.length());

            artist = tag.getFirst(FieldKey.ARTIST);
            mArtistEditText.setText(artist);
            mArtistEditText.setSelection(artist.length());

            album = tag.getFirst(FieldKey.ALBUM);
            mAlbumEditText.setText(album);
            mAlbumEditText.setSelection(album.length());


            albumArtist = tag.getFirst(FieldKey.ALBUM_ARTIST);
            mAlbumArtistEditText.setText(albumArtist);
            mAlbumArtistEditText.setSelection(albumArtist.length());


            genre = tag.getFirst(FieldKey.GENRE);
            mGenreEditText.setText(genre);
            mGenreEditText.setSelection(genre.length());

            producer = tag.getFirst(FieldKey.PRODUCER);
            mProducerEditText.setText(producer);
            mProducerEditText.setSelection(mProducerEditText.length());

            year = tag.getFirst(FieldKey.YEAR);
            mYearEditText.setText(year);
            mYearEditText.setSelection(year.length());

            track = tag.getFirst(FieldKey.TRACK);
            mTrackEditText.setText(track);
            mTrackEditText.setSelection(track.length());


            totalTrack = tag.getFirst(FieldKey.TRACK_TOTAL);
            mTotalTrackEditText.setText(totalTrack);
            mTotalTrackEditText.setSelection(totalTrack.length());

            comment = tag.getFirst(FieldKey.COMMENT);
            mCommentsEditText.setText(comment);
            mCommentsEditText.setSelection(comment.length());


            List<Artwork> artwork = tag.getArtworkList();

            if (artwork.size() > 0) {
                byte[] image = artwork.get(0).getBinaryData();
                Bitmap bitmap = BitmapFactory.decodeByteArray(image, 0, image.length);
//                mCardView.setCardBackgroundColor(Palette.from(bitmap).generate().getC(R.color.deep_purple));
                mAlbumArtImage.setImageBitmap(bitmap);
            }
        } catch (CannotReadException | IOException | TagException | ReadOnlyFileException | InvalidAudioFrameException e) {
            e.printStackTrace();
            Toast.makeText(this, R.string.track_is_malformed, Toast.LENGTH_SHORT).show();
            finish();
        }
    }
 
Example 24
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    final Activity context = getActivity();
    final Song song = getArguments().getParcelable("song");

    MaterialDialog dialog = new MaterialDialog.Builder(context)
            .customView(R.layout.dialog_file_details, true)
            .title(context.getResources().getString(R.string.label_details))
            .positiveText(android.R.string.ok)
            .build();

    View dialogView = dialog.getCustomView();
    final TextView fileName = dialogView.findViewById(R.id.file_name);
    final TextView filePath = dialogView.findViewById(R.id.file_path);
    final TextView fileSize = dialogView.findViewById(R.id.file_size);
    final TextView fileFormat = dialogView.findViewById(R.id.file_format);
    final TextView trackLength = dialogView.findViewById(R.id.track_length);
    final TextView bitRate = dialogView.findViewById(R.id.bitrate);
    final TextView samplingRate = dialogView.findViewById(R.id.sampling_rate);

    fileName.setText(makeTextWithTitle(context, R.string.label_file_name, "-"));
    filePath.setText(makeTextWithTitle(context, R.string.label_file_path, "-"));
    fileSize.setText(makeTextWithTitle(context, R.string.label_file_size, "-"));
    fileFormat.setText(makeTextWithTitle(context, R.string.label_file_format, "-"));
    trackLength.setText(makeTextWithTitle(context, R.string.label_track_length, "-"));
    bitRate.setText(makeTextWithTitle(context, R.string.label_bit_rate, "-"));
    samplingRate.setText(makeTextWithTitle(context, R.string.label_sampling_rate, "-"));

    try {
        if (song != null) {
            final File songFile = new File(song.data);
            if (songFile.exists()) {
                AudioFile audioFile = AudioFileIO.read(songFile);
                AudioHeader audioHeader = audioFile.getAudioHeader();

                fileName.setText(makeTextWithTitle(context, R.string.label_file_name, songFile.getName()));
                filePath.setText(makeTextWithTitle(context, R.string.label_file_path, songFile.getAbsolutePath()));
                fileSize.setText(makeTextWithTitle(context, R.string.label_file_size, getFileSizeString(songFile.length())));
                fileFormat.setText(makeTextWithTitle(context, R.string.label_file_format, audioHeader.getFormat()));
                trackLength.setText(makeTextWithTitle(context, R.string.label_track_length, MusicUtil.getReadableDurationString(audioHeader.getTrackLength() * 1000)));
                bitRate.setText(makeTextWithTitle(context, R.string.label_bit_rate, audioHeader.getBitRate() + " kb/s"));
                samplingRate.setText(makeTextWithTitle(context, R.string.label_sampling_rate, audioHeader.getSampleRate() + " Hz"));
            }
        }
    } catch (@NonNull CannotReadException | IOException | TagException | ReadOnlyFileException | InvalidAudioFrameException e) {
        Log.e(TAG, "error while reading the song file", e);
    }
    return dialog;
}
 
Example 25
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    final Activity context = getActivity();
    final Song song = getArguments().getParcelable("song");

    MaterialDialog dialog = new MaterialDialog.Builder(context)
            .customView(R.layout.dialog_file_details, true)
            .title(context.getResources().getString(R.string.label_details))
            .positiveText(android.R.string.ok)
            .build();

    View dialogView = dialog.getCustomView();
    final TextView fileName = dialogView.findViewById(R.id.file_name);
    final TextView filePath = dialogView.findViewById(R.id.file_path);
    final TextView fileSize = dialogView.findViewById(R.id.file_size);
    final TextView fileFormat = dialogView.findViewById(R.id.file_format);
    final TextView trackLength = dialogView.findViewById(R.id.track_length);
    final TextView bitRate = dialogView.findViewById(R.id.bitrate);
    final TextView samplingRate = dialogView.findViewById(R.id.sampling_rate);
    final TextView replayGain = dialogView.findViewById(R.id.replay_gain);

    fileName.setText(makeTextWithTitle(context, R.string.label_file_name, "-"));
    filePath.setText(makeTextWithTitle(context, R.string.label_file_path, "-"));
    fileSize.setText(makeTextWithTitle(context, R.string.label_file_size, "-"));
    fileFormat.setText(makeTextWithTitle(context, R.string.label_file_format, "-"));
    trackLength.setText(makeTextWithTitle(context, R.string.label_track_length, "-"));
    bitRate.setText(makeTextWithTitle(context, R.string.label_bit_rate, "-"));
    samplingRate.setText(makeTextWithTitle(context, R.string.label_sampling_rate, "-"));
    replayGain.setText(makeTextWithTitle(context, R.string.label_replay_gain, "-"));

    if (song != null) {
        final File songFile = new File(song.data);
        if (songFile.exists()) {
            fileName.setText(makeTextWithTitle(context, R.string.label_file_name, songFile.getName()));
            filePath.setText(makeTextWithTitle(context, R.string.label_file_path, songFile.getAbsolutePath()));
            fileSize.setText(makeTextWithTitle(context, R.string.label_file_size, getFileSizeString(songFile.length())));
            try {
                AudioFile audioFile = AudioFileIO.read(songFile);
                AudioHeader audioHeader = audioFile.getAudioHeader();

                fileFormat.setText(makeTextWithTitle(context, R.string.label_file_format, audioHeader.getFormat()));
                trackLength.setText(makeTextWithTitle(context, R.string.label_track_length, MusicUtil.getReadableDurationString(audioHeader.getTrackLength() * 1000)));
                bitRate.setText(makeTextWithTitle(context, R.string.label_bit_rate, audioHeader.getBitRate() + " kb/s"));
                samplingRate.setText(makeTextWithTitle(context, R.string.label_sampling_rate, audioHeader.getSampleRate() + " Hz"));

                float rgTrack = song.getReplayGainTrack();
                float rgAlbum = song.getReplayGainAlbum();
                String replayGainValues = "";
                if (rgTrack != 0.0) {
                    replayGainValues += String.format("%s: %.2f dB ", context.getString(R.string.song), rgTrack);
                }
                if (rgAlbum != 0.0) {
                    replayGainValues += String.format("%s: %.2f dB ", context.getString(R.string.album), rgAlbum);
                }
                if (replayGainValues.equals("")) {
                    replayGainValues = context.getString(R.string.none);
                }
                replayGain.setText(makeTextWithTitle(context, R.string.label_replay_gain, replayGainValues));
            } catch (@NonNull CannotReadException | IOException | TagException | ReadOnlyFileException | InvalidAudioFrameException e) {
                Log.e(TAG, "error while reading the song file", e);
                // fallback
                trackLength.setText(makeTextWithTitle(context, R.string.label_track_length, MusicUtil.getReadableDurationString(song.duration)));
            }
        } else {
            // fallback
            fileName.setText(makeTextWithTitle(context, R.string.label_file_name, song.title));
            trackLength.setText(makeTextWithTitle(context, R.string.label_track_length, MusicUtil.getReadableDurationString(song.duration)));
        }
    }

    return dialog;
}
 
Example 26
Source Project: VinylMusicPlayer   Source File: SAFUtil.java    License: GNU General Public License v3.0 4 votes vote down vote up
public static boolean isSAFRequired(AudioFile audio) {
    return isSAFRequired(audio.getFile());
}
 
Example 27
Source Project: VinylMusicPlayer   Source File: SAFUtil.java    License: GNU General Public License v3.0 4 votes vote down vote up
public static void writeFile(AudioFile audio) throws CannotWriteException {
    audio.commit();
}
 
Example 28
Source Project: subsonic   Source File: JaudiotaggerParser.java    License: GNU General Public License v3.0 4 votes vote down vote up
private Artwork getArtwork(MediaFile file) throws Exception {
    AudioFile audioFile = AudioFileIO.read(file.getFile());
    Tag tag = audioFile.getTag();
    return tag == null ? null : tag.getFirstArtwork();
}
 
Example 29
Source Project: Phonograph   Source File: SongDetailDialog.java    License: GNU General Public License v3.0 4 votes vote down vote up
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    final Activity context = getActivity();
    final Song song = getArguments().getParcelable("song");

    MaterialDialog dialog = new MaterialDialog.Builder(context)
            .customView(R.layout.dialog_file_details, true)
            .title(context.getResources().getString(R.string.label_details))
            .positiveText(android.R.string.ok)
            .build();

    View dialogView = dialog.getCustomView();
    final TextView fileName = dialogView.findViewById(R.id.file_name);
    final TextView filePath = dialogView.findViewById(R.id.file_path);
    final TextView fileSize = dialogView.findViewById(R.id.file_size);
    final TextView fileFormat = dialogView.findViewById(R.id.file_format);
    final TextView trackLength = dialogView.findViewById(R.id.track_length);
    final TextView bitRate = dialogView.findViewById(R.id.bitrate);
    final TextView samplingRate = dialogView.findViewById(R.id.sampling_rate);

    fileName.setText(makeTextWithTitle(context, R.string.label_file_name, "-"));
    filePath.setText(makeTextWithTitle(context, R.string.label_file_path, "-"));
    fileSize.setText(makeTextWithTitle(context, R.string.label_file_size, "-"));
    fileFormat.setText(makeTextWithTitle(context, R.string.label_file_format, "-"));
    trackLength.setText(makeTextWithTitle(context, R.string.label_track_length, "-"));
    bitRate.setText(makeTextWithTitle(context, R.string.label_bit_rate, "-"));
    samplingRate.setText(makeTextWithTitle(context, R.string.label_sampling_rate, "-"));

    if (song != null) {
        final File songFile = new File(song.data);
        if (songFile.exists()) {
            fileName.setText(makeTextWithTitle(context, R.string.label_file_name, songFile.getName()));
            filePath.setText(makeTextWithTitle(context, R.string.label_file_path, songFile.getAbsolutePath()));
            fileSize.setText(makeTextWithTitle(context, R.string.label_file_size, getFileSizeString(songFile.length())));
            try {
                AudioFile audioFile = AudioFileIO.read(songFile);
                AudioHeader audioHeader = audioFile.getAudioHeader();

                fileFormat.setText(makeTextWithTitle(context, R.string.label_file_format, audioHeader.getFormat()));
                trackLength.setText(makeTextWithTitle(context, R.string.label_track_length, MusicUtil.getReadableDurationString(audioHeader.getTrackLength() * 1000)));
                bitRate.setText(makeTextWithTitle(context, R.string.label_bit_rate, audioHeader.getBitRate() + " kb/s"));
                samplingRate.setText(makeTextWithTitle(context, R.string.label_sampling_rate, audioHeader.getSampleRate() + " Hz"));
            } catch (@NonNull CannotReadException | IOException | TagException | ReadOnlyFileException | InvalidAudioFrameException e) {
                Log.e(TAG, "error while reading the song file", e);
                // fallback
                trackLength.setText(makeTextWithTitle(context, R.string.label_track_length, MusicUtil.getReadableDurationString(song.duration)));
            }
        } else {
            // fallback
            fileName.setText(makeTextWithTitle(context, R.string.label_file_name, song.title));
            trackLength.setText(makeTextWithTitle(context, R.string.label_track_length, MusicUtil.getReadableDurationString(song.duration)));
        }
    }

    return dialog;
}
 
Example 30
Source Project: MusicPlayer   Source File: Library.java    License: MIT License 4 votes vote down vote up
private static int writeXML(File directory, Document doc, Element songs, int i) {
    File[] files = directory.listFiles();

    for (File file : files) {
        if (file.isFile() && isSupportedFileType(file.getName())) {
            try {

                AudioFile audioFile = AudioFileIO.read(file);
                Tag tag = audioFile.getTag();
                AudioHeader header = audioFile.getAudioHeader();

                Element song = doc.createElement("song");
                songs.appendChild(song);

                Element id = doc.createElement("id");
                Element title = doc.createElement("title");
                Element artist = doc.createElement("artist");
                Element album = doc.createElement("album");
                Element length = doc.createElement("length");
                Element trackNumber = doc.createElement("trackNumber");
                Element discNumber = doc.createElement("discNumber");
                Element playCount = doc.createElement("playCount");
                Element playDate = doc.createElement("playDate");
                Element location = doc.createElement("location");

                id.setTextContent(Integer.toString(i++));
                title.setTextContent(tag.getFirst(FieldKey.TITLE));
                String artistTitle = tag.getFirst(FieldKey.ALBUM_ARTIST);
                if (artistTitle == null || artistTitle.equals("") || artistTitle.equals("null")) {
                    artistTitle = tag.getFirst(FieldKey.ARTIST);
                }
                artist.setTextContent(
                        (artistTitle == null || artistTitle.equals("") || artistTitle.equals("null")) ? "" : artistTitle
                );
                album.setTextContent(tag.getFirst(FieldKey.ALBUM));
                length.setTextContent(Integer.toString(header.getTrackLength()));
                String track = tag.getFirst(FieldKey.TRACK);
                trackNumber.setTextContent(
                        (track == null || track.equals("") || track.equals("null")) ? "0" : track
                );
                String disc = tag.getFirst(FieldKey.DISC_NO);
                discNumber.setTextContent(
                        (disc == null || disc.equals("") || disc.equals("null")) ? "0" : disc
                );
                playCount.setTextContent("0");
                playDate.setTextContent(LocalDateTime.now().toString());
                location.setTextContent(Paths.get(file.getAbsolutePath()).toString());

                song.appendChild(id);
                song.appendChild(title);
                song.appendChild(artist);
                song.appendChild(album);
                song.appendChild(length);
                song.appendChild(trackNumber);
                song.appendChild(discNumber);
                song.appendChild(playCount);
                song.appendChild(playDate);
                song.appendChild(location);

                task.updateProgress(i, Library.maxProgress);

            } catch (Exception ex) {

                ex.printStackTrace();
            }

        } else if (file.isDirectory()) {

            i = writeXML(file, doc, songs, i);
        }
    }
    return i;
}