Example usage for android.media MediaMetadataRetriever setDataSource

List of usage examples for android.media MediaMetadataRetriever setDataSource

Introduction

In this page you can find the example usage for android.media MediaMetadataRetriever setDataSource.

Prototype

public void setDataSource(MediaDataSource dataSource) throws IllegalArgumentException 

Source Link

Document

Sets the data source (MediaDataSource) to use.

Usage

From source file:com.xperia64.timidityae.MusicService.java

@SuppressLint("NewApi")
public void play() {
    if (playList != null && currSongNumber >= 0) {
        shouldAdvance = false;/*from  w w w. j a va 2s. c om*/
        death = true;
        fullStop = false;
        stop();
        death = false;
        Globals.shouldRestore = true;
        while (!death && ((Globals.isPlaying == 0 || JNIHandler.alternativeCheck == 333333))) {
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        if (!death) {
            MediaMetadataRetriever mmr = new MediaMetadataRetriever();
            String tmpTitle;
            Globals.currArt = null;
            final int songIndex;
            if (shuffleMode == 1) {
                songIndex = realSongNumber = shuffledIndices.get(currSongNumber);
            } else {
                songIndex = realSongNumber = currSongNumber;
            }
            try {
                mmr.setDataSource(playList.get(songIndex));
                tmpTitle = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE);
                if (tmpTitle != null) {
                    if (TextUtils.isEmpty(tmpTitle))
                        tmpTitle = playList.get(songIndex)
                                .substring(playList.get(songIndex).lastIndexOf('/') + 1);
                } else {
                    tmpTitle = playList.get(songIndex).substring(playList.get(songIndex).lastIndexOf('/') + 1);
                }

            } catch (RuntimeException e) {
                tmpTitle = playList.get(songIndex).substring(playList.get(songIndex).lastIndexOf('/') + 1);
            }
            boolean goodart = false;
            if (Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD_MR1) // Please work
            {
                try {

                    byte[] art = mmr.getEmbeddedPicture();
                    if (art != null) {
                        Globals.currArt = BitmapFactory.decodeByteArray(art, 0, art.length);
                        goodart = Globals.currArt != null;
                    }
                } catch (Exception e) {
                }
            }
            if (!goodart) {
                String goodPath = playList.get(songIndex).substring(0,
                        playList.get(songIndex).lastIndexOf('/') + 1) + "folder.jpg";
                if (new File(goodPath).exists()) {
                    try {
                        Globals.currArt = BitmapFactory.decodeFile(goodPath);
                    } catch (RuntimeException e) {
                    }
                } else {
                    // Try albumart.jpg
                    goodPath = playList.get(songIndex).substring(0,
                            playList.get(songIndex).lastIndexOf('/') + 1) + "AlbumArt.jpg";
                    if (new File(goodPath).exists()) {
                        try {
                            Globals.currArt = BitmapFactory.decodeFile(goodPath);
                        } catch (RuntimeException e) {
                            // 
                        }
                    }
                }
            }
            if (shouldDoWidget) {
                Intent intent = new Intent(this, TimidityAEWidgetProvider.class);
                intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
                // Use an array and EXTRA_APPWIDGET_IDS instead of AppWidgetManager.EXTRA_APPWIDGET_ID,
                // since it seems the onUpdate() is only fired on that:
                ids = AppWidgetManager.getInstance(getApplication())
                        .getAppWidgetIds(new ComponentName(getApplication(), TimidityAEWidgetProvider.class));

                //intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
                intent.putExtra("com.xperia64.timidityae.timidityaewidgetprovider.onlyart", true);
                sendBroadcast(intent);
            }
            Intent new_intent = new Intent();
            new_intent.setAction(getResources().getString(R.string.ta_rec));
            new_intent.putExtra(getResources().getString(R.string.ta_cmd), 6);
            sendBroadcast(new_intent);

            currTitle = tmpTitle;
            shouldAdvance = true;
            paused = false;

            final int x = JNIHandler.play(playList.get(songIndex));
            if (x != 0) {
                switch (x) {
                case -1:
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(), getResources().getString(R.string.srv_fnf),
                                    Toast.LENGTH_SHORT).show();
                        }
                    });

                    break;
                case -3:
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(),
                                    "Error initializing AudioTrack. Try decreasing the buffer size.",
                                    Toast.LENGTH_LONG).show();
                        }
                    });

                    break;
                case -9:
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(),
                                    getResources().getString(R.string.srv_loading), Toast.LENGTH_SHORT).show();
                        }
                    });
                    break;
                default:
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(),
                                    String.format(getResources().getString(R.string.srv_unk), x),
                                    Toast.LENGTH_SHORT).show();
                        }
                    });
                    break;
                }

                Globals.isPlaying = 1;
                JNIHandler.type = true;
                shouldAdvance = false;
                JNIHandler.paused = false;
                stop();
            } else {
                updateNotification(currTitle, paused);
                new Thread(new Runnable() {
                    public void run() {
                        while (!death && ((Globals.isPlaying == 1 && shouldAdvance))) {
                            if (JNIHandler.alternativeCheck == 555555)
                                death = true;

                            //System.out.println(String.format("alt check: %d death: %s isplaying: %d shouldAdvance: %s seekBarReady: %s",JNIHandler.alternativeCheck,death?"true":"false",Globals.isPlaying,shouldAdvance?"true":"false",JNIHandler.seekbarReady?"true":"false"));
                            try {
                                Thread.sleep(10);
                            } catch (InterruptedException e) {
                            }
                        }
                        if (!death) {
                            Intent new_intent = new Intent();
                            new_intent.setAction(getResources().getString(R.string.ta_rec));
                            new_intent.putExtra(getResources().getString(R.string.ta_cmd), 0);
                            new_intent.putExtra(getResources().getString(R.string.ta_startt),
                                    JNIHandler.maxTime);
                            new_intent.putExtra(getResources().getString(R.string.ta_songttl), currTitle);
                            new_intent.putExtra(getResources().getString(R.string.ta_filename),
                                    playList.get(songIndex));
                            new_intent.putExtra("stupidNumber", songIndex);
                            sendBroadcast(new_intent);
                        }
                        if (new File(playList.get(songIndex) + ".def.tcf").exists()
                                || new File(playList.get(songIndex) + ".def.tzf").exists()) {
                            String suffix;
                            if (new File(playList.get(songIndex) + ".def.tcf").exists()
                                    && new File(playList.get(songIndex) + ".def.tzf").exists()) {
                                suffix = (Globals.compressCfg ? ".def.tzf" : ".def.tcf");
                            } else if (new File(playList.get(songIndex) + ".def.tcf").exists()) {
                                suffix = ".def.tcf";
                            } else {
                                suffix = ".def.tzf";
                            }
                            JNIHandler.shouldPlayNow = false;
                            JNIHandler.currTime = 0;
                            while (Globals.isPlaying == 0 && !death && shouldAdvance
                                    && !JNIHandler.dataWritten) {
                                try {
                                    Thread.sleep(25);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                            }
                            Intent new_intent = new Intent(); // silly, but should be done async. I think.
                            new_intent.setAction(getResources().getString(R.string.msrv_rec));
                            new_intent.putExtra(getResources().getString(R.string.msrv_cmd), 17);
                            new_intent.putExtra(getResources().getString(R.string.msrv_infile),
                                    playList.get(songIndex) + suffix);
                            new_intent.putExtra(getResources().getString(R.string.msrv_reset), true);
                            sendBroadcast(new_intent);
                        }
                        while (!death && (((Globals.isPlaying == 0 || JNIHandler.alternativeCheck == 333333)
                                && shouldAdvance))) {
                            try {
                                Thread.sleep(25);
                            } catch (InterruptedException e) {
                            }
                        }
                        if (shouldAdvance && !death) {
                            shouldAdvance = false;
                            new Thread(new Runnable() {
                                public void run() {
                                    if (playList.size() > 1
                                            && (((songIndex + 1 < playList.size() && loopMode == 0))
                                                    || loopMode == 1)) {
                                        next();
                                    } else if (loopMode == 2 || playList.size() == 1) {
                                        play();
                                    } else if (loopMode == 0) {
                                        Globals.hardStop = true;
                                        Intent new_intent = new Intent();
                                        new_intent.setAction(getResources().getString(R.string.ta_rec));
                                        new_intent.putExtra(getResources().getString(R.string.ta_cmd), 5);
                                        new_intent.putExtra(getResources().getString(R.string.ta_pause), false);
                                        sendBroadcast(new_intent);
                                    }
                                }
                            }).start();

                        }

                    }
                }).start();
            }
        }
    }
}

From source file:github.daneren2005.dsub.fragments.SubsonicFragment.java

public void displaySongInfo(final Entry song) {
    Integer duration = null;/* w w w  .  jav a2 s  .  c o  m*/
    Integer bitrate = null;
    String format = null;
    long size = 0;
    if (!song.isDirectory()) {
        try {
            DownloadFile downloadFile = new DownloadFile(context, song, false);
            File file = downloadFile.getCompleteFile();
            if (file.exists()) {
                MediaMetadataRetriever metadata = new MediaMetadataRetriever();
                metadata.setDataSource(file.getAbsolutePath());

                String tmp = metadata.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
                duration = Integer.parseInt((tmp != null) ? tmp : "0") / 1000;
                format = FileUtil.getExtension(file.getName());
                size = file.length();

                // If no duration try to read bitrate tag
                if (duration == null) {
                    tmp = metadata.extractMetadata(MediaMetadataRetriever.METADATA_KEY_BITRATE);
                    bitrate = Integer.parseInt((tmp != null) ? tmp : "0") / 1000;
                } else {
                    // Otherwise do a calculation for it
                    // Divide by 1000 so in kbps
                    bitrate = (int) (size / duration) / 1000 * 8;
                }

                if (Util.isOffline(context)) {
                    song.setGenre(metadata.extractMetadata(MediaMetadataRetriever.METADATA_KEY_GENRE));
                    String year = metadata.extractMetadata(MediaMetadataRetriever.METADATA_KEY_YEAR);
                    song.setYear(Integer.parseInt((year != null) ? year : "0"));
                }
            }
        } catch (Exception e) {
            Log.i(TAG, "Device doesn't properly support MediaMetadataRetreiver");
        }
    }
    if (duration == null) {
        duration = song.getDuration();
    }

    List<Integer> headers = new ArrayList<>();
    List<String> details = new ArrayList<>();

    if (!song.isDirectory()) {
        headers.add(R.string.details_title);
        details.add(song.getTitle());
    }

    if (song instanceof PodcastEpisode) {
        headers.add(R.string.details_podcast);
        details.add(song.getArtist());

        headers.add(R.string.details_status);
        details.add(((PodcastEpisode) song).getStatus());
    } else if (!song.isVideo()) {
        if (song.getArtist() != null && !"".equals(song.getArtist())) {
            headers.add(R.string.details_artist);
            details.add(song.getArtist());
        }
        if (song.getAlbum() != null && !"".equals(song.getAlbum())) {
            headers.add(R.string.details_album);
            details.add(song.getAlbum());
        }
    }
    if (song.getTrack() != null && song.getTrack() != 0) {
        headers.add(R.string.details_track);
        details.add(Integer.toString(song.getTrack()));
    }
    if (song.getGenre() != null && !"".equals(song.getGenre())) {
        headers.add(R.string.details_genre);
        details.add(song.getGenre());
    }
    if (song.getYear() != null && song.getYear() != 0) {
        headers.add(R.string.details_year);
        details.add(Integer.toString(song.getYear()));
    }
    if (!Util.isOffline(context) && song.getSuffix() != null) {
        headers.add(R.string.details_server_format);
        details.add(song.getSuffix());

        if (song.getBitRate() != null && song.getBitRate() != 0) {
            headers.add(R.string.details_server_bitrate);
            details.add(song.getBitRate() + " kbps");
        }
    }
    if (format != null && !"".equals(format)) {
        headers.add(R.string.details_cached_format);
        details.add(format);
    }
    if (bitrate != null && bitrate != 0) {
        headers.add(R.string.details_cached_bitrate);
        details.add(bitrate + " kbps");
    }
    if (size != 0) {
        headers.add(R.string.details_size);
        details.add(Util.formatLocalizedBytes(size, context));
    }
    if (duration != null && duration != 0) {
        headers.add(R.string.details_length);
        details.add(Util.formatDuration(duration));
    }
    if (song.getBookmark() != null) {
        headers.add(R.string.details_bookmark_position);
        details.add(Util.formatDuration(song.getBookmark().getPosition() / 1000));
    }
    if (song.getRating() != 0) {
        headers.add(R.string.details_rating);
        details.add(song.getRating() + " stars");
    }

    headers.add(R.string.details_starred);
    details.add(Util.formatBoolean(context, song.isStarred()));

    if (song instanceof PodcastEpisode) {
        headers.add(R.string.details_description);
        details.add(song.getAlbum());
    }

    int title;
    if (song.isDirectory()) {
        title = R.string.details_title_album;
    } else if (song instanceof PodcastEpisode) {
        title = R.string.details_title_podcast;
    } else {
        title = R.string.details_title_song;
    }
    Util.showDetailsDialog(context, title, headers, details);
}

From source file:github.popeen.dsub.fragments.SubsonicFragment.java

public void displaySongInfo(final Entry song) {
    Integer duration = null;/*from  ww  w.j a va  2  s .c o m*/
    Integer bitrate = null;
    String format = null;
    long size = 0;
    if (!song.isDirectory()) {
        try {
            DownloadFile downloadFile = new DownloadFile(context, song, false);
            File file = downloadFile.getCompleteFile();
            if (file.exists()) {
                MediaMetadataRetriever metadata = new MediaMetadataRetriever();
                metadata.setDataSource(file.getAbsolutePath());

                String tmp = metadata.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
                duration = Integer.parseInt((tmp != null) ? tmp : "0") / 1000;
                format = FileUtil.getExtension(file.getName());
                size = file.length();

                // If no duration try to read bitrate tag
                if (duration == null) {
                    tmp = metadata.extractMetadata(MediaMetadataRetriever.METADATA_KEY_BITRATE);
                    bitrate = Integer.parseInt((tmp != null) ? tmp : "0") / 1000;
                } else {
                    // Otherwise do a calculation for it
                    // Divide by 1000 so in kbps
                    bitrate = (int) (size / duration) / 1000 * 8;
                }

                if (Util.isOffline(context)) {
                    song.setGenre(metadata.extractMetadata(MediaMetadataRetriever.METADATA_KEY_GENRE));
                    String year = metadata.extractMetadata(MediaMetadataRetriever.METADATA_KEY_YEAR);
                    song.setYear(Integer.parseInt((year != null) ? year : "0"));
                }
            }
        } catch (Exception e) {
            Log.i(TAG, "Device doesn't properly support MediaMetadataRetreiver");
        }
    }
    if (duration == null) {
        duration = song.getDuration();
    }

    List<Integer> headers = new ArrayList<>();
    List<String> details = new ArrayList<>();

    if (!song.isDirectory()) {
        headers.add(R.string.details_title);
        details.add(song.getTitle());
    }

    if (song instanceof PodcastEpisode) {
        headers.add(R.string.details_podcast);
        details.add(song.getArtist());

        headers.add(R.string.details_status);
        details.add(((PodcastEpisode) song).getStatus());
    } else if (!song.isVideo()) {
        if (song.getArtist() != null && !"".equals(song.getArtist())) {
            headers.add(R.string.details_artist);
            details.add(song.getArtist());
        }
        if (song.getAlbum() != null && !"".equals(song.getAlbum())) {
            headers.add(R.string.details_album);
            details.add(song.getAlbum());
        }
    }
    if (song.getTrack() != null && song.getTrack() != 0) {
        headers.add(R.string.details_track);
        details.add(Integer.toString(song.getTrack()));
    }
    if (song.getGenre() != null && !"".equals(song.getGenre())) {
        headers.add(R.string.details_genre);
        details.add(song.getGenre());
    }
    if (song.getYear() != null && song.getYear() != 0) {
        headers.add(R.string.details_year);
        details.add(Integer.toString(song.getYear()));
    }
    if (!Util.isOffline(context) && song.getSuffix() != null) {
        headers.add(R.string.details_server_format);
        details.add(song.getSuffix());

        if (song.getBitRate() != null && song.getBitRate() != 0) {
            headers.add(R.string.details_server_bitrate);
            details.add(song.getBitRate() + " kbps");
        }
    }
    if (format != null && !"".equals(format)) {
        headers.add(R.string.details_cached_format);
        details.add(format);
    }
    if (bitrate != null && bitrate != 0) {
        headers.add(R.string.details_cached_bitrate);
        details.add(bitrate + " kbps");
    }
    if (size != 0) {
        headers.add(R.string.details_size);
        details.add(Util.formatLocalizedBytes(size, context));
    }
    if (duration != null && duration != 0) {
        headers.add(R.string.details_length);
        details.add(Util.formatDuration(duration));
    }
    if (song.getBookmark() != null) {
        headers.add(R.string.details_bookmark_position);
        details.add(Util.formatDuration(song.getBookmark().getPosition() / 1000));
    }
    if (song.getRating() != 0) {
        headers.add(R.string.details_rating);
        details.add(song.getRating() + " stars");
    }

    headers.add(R.string.details_starred);
    details.add(Util.formatBoolean(context, song.isStarred()));

    try {
        Long[] dates = SongDBHandler.getHandler(context).getLastPlayed(song);
        if (dates != null && dates[0] != null && dates[0] > 0) {
            headers.add(R.string.details_last_played);
            details.add(Util.formatDate((dates[1] != null && dates[1] > dates[0]) ? dates[1] : dates[0]));
        }
    } catch (Exception e) {
        Log.e(TAG, "Failed to get last played", e);
    }

    if (song instanceof PodcastEpisode) {
        headers.add(R.string.details_description);
        details.add(song.getAlbum());
    }

    int title;
    if (song.isDirectory()) {
        title = R.string.details_title_album;
    } else if (song instanceof PodcastEpisode) {
        title = R.string.details_title_podcast;
    } else {
        title = R.string.details_title_song;
    }
    Util.showDetailsDialog(context, title, headers, details);
}

From source file:com.aimfire.demo.CamcorderActivity.java

private void generateThumbAndPreview(String filePath) {
    if (BuildConfig.DEBUG)
        Log.d(TAG, "generateThumbAndPreview");

    String movieNameNoExt = MediaScanner.getMovieNameNoExt(filePath);
    String previewPath = MainConsts.MEDIA_3D_THUMB_PATH + movieNameNoExt + ".jpeg";
    String thumbPath = MainConsts.MEDIA_3D_THUMB_PATH + movieNameNoExt + ".jpg";

    MediaMetadataRetriever retriever = new MediaMetadataRetriever();

    Bitmap bitmap = null;//from ww w. j ava2s .c o  m

    try {
        FileInputStream inputStream = new FileInputStream(filePath);
        retriever.setDataSource(inputStream.getFD());
        inputStream.close();

        bitmap = retriever.getFrameAtTime(0L, MediaMetadataRetriever.OPTION_CLOSEST_SYNC);
        retriever.release();

        if (bitmap != null) {
            FileOutputStream out = null;
            out = new FileOutputStream(previewPath);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 95, out);
            out.close();

            Bitmap thumbnail = ThumbnailUtils.extractThumbnail(bitmap, MainConsts.THUMBNAIL_SIZE,
                    MainConsts.THUMBNAIL_SIZE);
            out = new FileOutputStream(thumbPath);
            thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, out);
            out.close();
        }
    } catch (Exception e) {
        if (BuildConfig.DEBUG)
            Log.e(TAG, "generateThumbAndPreview: exception" + e.getMessage());
        retriever.release();
        FirebaseCrash.report(e);
    }
}