Example usage for android.media MediaMetadataRetriever extractMetadata

List of usage examples for android.media MediaMetadataRetriever extractMetadata

Introduction

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

Prototype

public native String extractMetadata(int keyCode);

Source Link

Document

Call this method after setDataSource().

Usage

From source file:at.ac.tuwien.detlef.fragments.PlayerFragment.java

private void setNotPlayingSeekBarAndTime(Episode ep) {
    if (service == null) {
        return;//from   www.  ja v  a2 s  .com
    }
    if (trackingTouch) {
        return;
    }
    try {
        if (service.episodeFileOK(ep)) {
            MediaMetadataRetriever metaData = new MediaMetadataRetriever();
            metaData.setDataSource(ep.getFilePath());
            String durationString = metaData.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
            int duration = Integer.parseInt(durationString);
            int playingPosition = ep.getPlayPosition();
            int pos = 0;
            if (((playingPosition) > 0) && (playingPosition < duration)) {
                pos = playingPosition;
            }
            String minutesSecondsRemaining = getRemainingTime(duration, pos);
            String minutesSecondsAlreadyPlayed = getAlreadyPlayed(pos);
            remainingTime.setText("-" + minutesSecondsRemaining);
            alreadyPlayed.setText(minutesSecondsAlreadyPlayed);
            seekBar.setMax(duration);
            seekBar.setProgress(pos);
            seekBar.setSecondaryProgress(0);
        } else if ((service.getNextEpisode() == ep) && service.hasRunningEpisode()) {
            seekBar.setMax(service.getDuration());
            seekBar.setProgress(service.getCurrentPosition());
            alreadyPlayed.setText(getAlreadyPlayed(service.getCurrentPosition()));
            remainingTime.setText("-" + getRemainingTime(service.getDuration(), service.getCurrentPosition()));
        }
    } catch (Exception ex) {
        Log.d(getClass().getName(), "Error while retrieving duration of episode: " + ex.getMessage());
    }
}

From source file:com.android.camera.manager.ThumbnailViewManager.java

private String getMimeType(String filePath) {
    MediaMetadataRetriever retriever = new MediaMetadataRetriever();
    String mime = "image/jpeg";
    if (filePath != null) {
        try {/* w  w w.  ja v a2s  .co  m*/
            retriever.setDataSource(filePath);
            mime = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_MIMETYPE);
        } catch (IllegalStateException e) {
            return mime;
        } catch (IllegalArgumentException e) {
            return mime;
        } catch (RuntimeException e) {
            return mime;
        }
    }
    Log.d(TAG, "[getMimeType] mime = " + mime);
    return mime;
}

From source file:com.aengbee.android.leanback.ui.VideoDetailsFragment.java

public int getDurationVideo(File videoFile) {
    MediaMetadataRetriever retriever = new MediaMetadataRetriever();
    retriever.setDataSource(getActivity(), Uri.fromFile(videoFile));
    String time = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
    int sec = (int) Long.parseLong(time) / 1000;
    return sec;//from  www .j a va 2s.com
}

From source file:com.aniruddhc.acemusic.player.NowPlayingActivity.PlaylistPagerFlippedFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    final ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_playlist_pager_flipped, container,
            false);/*ww  w .  j  a  v a  2 s . co  m*/
    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;
}

From source file:life.knowledge4.videotrimmer.K4LVideoTrimmer.java

public void onSaveClicked() {
    if (mOnTrimVideoListener != null && !mOnTrimVideoListener.shouldTrim()) {
        onTrimFinished();/*from  w ww.j av  a  2 s.com*/
        return;
    }

    if (mStartPosition <= 0 && mEndPosition >= mDuration) {
        if (mOnTrimVideoListener != null)
            mOnTrimVideoListener.getResult(mSrc);
    } else {
        mPlayView.setVisibility(View.VISIBLE);
        mVideoView.pause();

        MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
        mediaMetadataRetriever.setDataSource(getContext(), mSrc);
        long METADATA_KEY_DURATION = Long.parseLong(
                mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION));

        final File file = new File(mSrc.getPath());

        if (mTimeVideo < MIN_TIME_FRAME) {

            if ((METADATA_KEY_DURATION - mEndPosition) > (MIN_TIME_FRAME - mTimeVideo)) {
                mEndPosition += (MIN_TIME_FRAME - mTimeVideo);
            } else if (mStartPosition > (MIN_TIME_FRAME - mTimeVideo)) {
                mStartPosition -= (MIN_TIME_FRAME - mTimeVideo);
            }
        }

        Log.d(TAG, "onSaveClicked: mStartPosition: " + stringForTime(mStartPosition) + " #### mEndPosition: "
                + stringForTime(mEndPosition));

        final File root = new File(Environment.getExternalStorageDirectory() + File.separator
                + "k4lVideoTrimmer" + File.separator);
        root.mkdirs();
        final String fname = "t_" + mSrc.getPath().substring(mSrc.getPath().lastIndexOf("/") + 1);
        final File sdImageMainDirectory = new File(root, fname);
        final Uri outputFileUri = Uri.fromFile(sdImageMainDirectory);

        final String outPutPath = getRealPathFromUri(outputFileUri);

        FFmpeg ffmpeg = FFmpeg.getInstance(getContext());
        String[] command = { "-y", "-i", file.getPath(), "-ss", stringForTime(mStartPosition), "-to",
                stringForTime(mEndPosition), "-c", "copy", outPutPath };//{"-y", "-ss", "00:00:03", "-i", file.getPath(), "-t", "00:00:08", "-async", "1", outPutPath};  //-i movie.mp4 -ss 00:00:03 -t 00:00:08 -async 1 cut.mp4
        try {
            ffmpeg.execute(command, new ExecuteBinaryResponseHandler() {
                @Override
                public void onSuccess(String message) {
                    super.onSuccess(message);
                    Log.d(TAG, "onSuccess: " + message);
                }

                @Override
                public void onProgress(String message) {
                    super.onProgress(message);
                    Log.d(TAG, "onProgress: " + message);
                }

                @Override
                public void onFailure(String message) {
                    super.onFailure(message);
                    loading.setVisibility(GONE);
                    Log.d(TAG, "onFailure: " + message);
                }

                @Override
                public void onStart() {
                    super.onStart();
                    Log.d(TAG, "onStart: ");
                }

                @Override
                public void onFinish() {
                    super.onFinish();
                    loading.setVisibility(GONE);
                    mOnTrimVideoListener.getResult(outputFileUri);
                    Log.d(TAG, "onFinish: ");
                }
            });
        } catch (FFmpegCommandAlreadyRunningException e) {

        }

        //notify that video trimming started
        if (mOnTrimVideoListener != null)
            mOnTrimVideoListener.onTrimStarted();
        //<<<<<<< HEAD
        //=======
        //
        //            BackgroundExecutor.execute(
        //                    new BackgroundExecutor.Task("", 0L, "") {
        //                        @Override
        //                        public void execute() {
        //                            try {
        //                                TrimVideoUtils.startTrim(file, new File(getDestinationPath(), UUID.randomUUID().toString()), mStartPosition, mEndPosition, mOnTrimVideoListener);
        //                            } catch (final Throwable e) {
        //                                Thread.getDefaultUncaughtExceptionHandler().uncaughtException(Thread.currentThread(), e);
        //                            }
        //                        }
        //                    }
        //            );
        //>>>>>>> e9b3dcbb38ccfa62307fc2fb020bcb4d35933afa
    }
}

From source file:org.runbuddy.tomahawk.activities.TomahawkMainActivity.java

private void handleIntent(Intent intent) {
    if (MediaStore.INTENT_ACTION_MEDIA_PLAY_FROM_SEARCH.equals(intent.getAction())) {
        intent.setAction(null);//from w  ww.j a v  a 2  s  .  co m
        String playbackManagerId = getSupportMediaController().getExtras()
                .getString(PlaybackService.EXTRAS_KEY_PLAYBACKMANAGER);
        PlaybackManager playbackManager = PlaybackManager.getByKey(playbackManagerId);
        MediaPlayIntentHandler intentHandler = new MediaPlayIntentHandler(
                getSupportMediaController().getTransportControls(), playbackManager);
        intentHandler.mediaPlayFromSearch(intent.getExtras());
    }
    if ("com.google.android.gms.actions.SEARCH_ACTION".equals(intent.getAction())) {
        intent.setAction(null);
        String query = intent.getStringExtra(SearchManager.QUERY);
        if (query != null && !query.isEmpty()) {
            DatabaseHelper.get().addEntryToSearchHistory(query);
            Bundle bundle = new Bundle();
            bundle.putString(TomahawkFragment.QUERY_STRING, query);
            bundle.putInt(TomahawkFragment.CONTENT_HEADER_MODE, ContentHeaderFragment.MODE_HEADER_STATIC);
            FragmentUtils.replace(TomahawkMainActivity.this, SearchPagerFragment.class, bundle);
        }
    }
    if (SHOW_PLAYBACKFRAGMENT_ON_STARTUP.equals(intent.getAction())) {
        intent.setAction(null);
        // if this Activity is being shown after the user clicked the notification
        if (mSlidingUpPanelLayout != null) {
            mSlidingUpPanelLayout.setPanelState(SlidingUpPanelLayout.PanelState.EXPANDED);
        }
    }
    if (intent.hasExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE)) {
        intent.removeExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE);
        Bundle bundle = new Bundle();
        bundle.putInt(TomahawkFragment.CONTENT_HEADER_MODE, ContentHeaderFragment.MODE_HEADER_STATIC_SMALL);
        FragmentUtils.replace(this, PreferencePagerFragment.class, bundle);
    }

    if (intent.getData() != null) {
        final Uri data = intent.getData();
        intent.setData(null);
        List<String> pathSegments = data.getPathSegments();
        String host = data.getHost();
        String scheme = data.getScheme();
        if ((scheme != null && (scheme.equals("spotify") || scheme.equals("tomahawk"))) || (host != null
                && (host.contains("spotify.com") || host.contains("hatchet.is") || host.contains("toma.hk")
                        || host.contains("beatsmusic.com") || host.contains("deezer.com")
                        || host.contains("rdio.com") || host.contains("soundcloud.com")))) {
            PipeLine.get().lookupUrl(data.toString());
        } else if ((pathSegments != null && pathSegments.get(pathSegments.size() - 1).endsWith(".xspf"))
                || (intent.getType() != null && intent.getType().equals("application/xspf+xml"))) {
            TomahawkRunnable r = new TomahawkRunnable(TomahawkRunnable.PRIORITY_IS_INFOSYSTEM_HIGH) {
                @Override
                public void run() {
                    Playlist pl = XspfParser.parse(data);
                    if (pl != null) {
                        final Bundle bundle = new Bundle();
                        bundle.putString(TomahawkFragment.PLAYLIST, pl.getCacheKey());
                        bundle.putInt(TomahawkFragment.CONTENT_HEADER_MODE,
                                ContentHeaderFragment.MODE_HEADER_DYNAMIC);
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                FragmentUtils.replace(TomahawkMainActivity.this, PlaylistEntriesFragment.class,
                                        bundle);
                            }
                        });
                    }
                }
            };
            ThreadManager.get().execute(r);
        } else if (pathSegments != null && (pathSegments.get(pathSegments.size() - 1).endsWith(".axe")
                || pathSegments.get(pathSegments.size() - 1).endsWith(".AXE"))) {
            InstallPluginConfigDialog dialog = new InstallPluginConfigDialog();
            Bundle args = new Bundle();
            args.putString(InstallPluginConfigDialog.PATH_TO_AXE_URI_STRING, data.toString());
            dialog.setArguments(args);
            dialog.show(getSupportFragmentManager(), null);
        } else {
            String albumName;
            String trackName;
            String artistName;
            try {
                MediaMetadataRetriever retriever = new MediaMetadataRetriever();
                retriever.setDataSource(this, data);
                albumName = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUM);
                artistName = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST);
                trackName = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE);
                retriever.release();
            } catch (Exception e) {
                Log.e(TAG, "handleIntent: " + e.getClass() + ": " + e.getLocalizedMessage());
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        String msg = TomahawkApp.getContext().getString(R.string.invalid_file);
                        Toast.makeText(TomahawkApp.getContext(), msg, Toast.LENGTH_LONG).show();
                    }
                });
                return;
            }
            if (TextUtils.isEmpty(trackName) && pathSegments != null) {
                trackName = pathSegments.get(pathSegments.size() - 1);
            }
            Query query = Query.get(trackName, albumName, artistName, false);
            Result result = Result.get(data.toString(), query.getBasicTrack(),
                    UserCollectionStubResolver.get());
            float trackScore = query.howSimilar(result);
            query.addTrackResult(result, trackScore);
            Bundle bundle = new Bundle();
            List<Query> queries = new ArrayList<>();
            queries.add(query);
            Playlist playlist = Playlist.fromQueryList(IdGenerator.getSessionUniqueStringId(), "", "", queries);
            playlist.setFilled(true);
            playlist.setName(artistName + " - " + trackName);
            bundle.putString(TomahawkFragment.PLAYLIST, playlist.getCacheKey());
            bundle.putInt(TomahawkFragment.CONTENT_HEADER_MODE, ContentHeaderFragment.MODE_HEADER_DYNAMIC);
            FragmentUtils.replace(TomahawkMainActivity.this, PlaylistEntriesFragment.class, bundle);
        }
    }
}

From source file:com.sebible.cordova.videosnapshot.VideoSnapshot.java

/**
 * Take snapshots of a video file//from   w  ww  .jav  a 2s.com
 *
 * @param source path of the file
 * @param count of snapshots that are gonna be taken
 */
private void snapshot(final JSONObject options) {
    final CallbackContext context = this.callbackContext;
    this.cordova.getThreadPool().execute(new Runnable() {
        public void run() {
            MediaMetadataRetriever retriever = new MediaMetadataRetriever();
            try {
                int count = options.optInt("count", 1);
                int countPerMinute = options.optInt("countPerMinute", 0);
                int quality = options.optInt("quality", 90);
                String source = options.optString("source", "");
                Boolean timestamp = options.optBoolean("timeStamp", true);
                String prefix = options.optString("prefix", "");
                int textSize = options.optInt("textSize", 48);

                if (source.isEmpty()) {
                    throw new Exception("No source provided");
                }

                JSONObject obj = new JSONObject();
                obj.put("result", false);
                JSONArray results = new JSONArray();

                Log.i("snapshot", "Got source: " + source);
                Uri p = Uri.parse(source);
                String filename = p.getLastPathSegment();

                FileInputStream in = new FileInputStream(new File(p.getPath()));
                retriever.setDataSource(in.getFD());
                String tmp = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
                long duration = Long.parseLong(tmp);
                if (countPerMinute > 0) {
                    count = (int) (countPerMinute * duration / (60 * 1000));
                }
                if (count < 1) {
                    count = 1;
                }
                long delta = duration / (count + 1); // Start at duration * 1 and ends at duration * count
                if (delta < 1000) { // min 1s
                    delta = 1000;
                }

                Log.i("snapshot", "duration:" + duration + " delta:" + delta);

                File storage = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
                for (int i = 1; delta * i < duration && i <= count; i++) {
                    String filename2 = filename.replace('.', '_') + "-snapshot" + i + ".jpg";
                    File dest = new File(storage, filename2);
                    if (!storage.exists() && !storage.mkdirs()) {
                        throw new Exception("Unable to access storage:" + storage.getPath());
                    }
                    FileOutputStream out = new FileOutputStream(dest);
                    Bitmap bm = retriever.getFrameAtTime(i * delta * 1000);
                    if (timestamp) {
                        drawTimestamp(bm, prefix, delta * i, textSize);
                    }
                    bm.compress(Bitmap.CompressFormat.JPEG, quality, out);
                    out.flush();
                    out.close();
                    results.put(dest.getAbsolutePath());
                }

                obj.put("result", true);
                obj.put("snapshots", results);
                context.success(obj);
            } catch (Exception ex) {
                ex.printStackTrace();
                Log.e("snapshot", "Exception:", ex);
                fail("Exception: " + ex.toString());
            } finally {
                try {
                    retriever.release();
                } catch (RuntimeException ex) {
                }
            }
        }
    });
}

From source file:org.tomahawk.tomahawk_android.activities.TomahawkMainActivity.java

private void handleIntent(Intent intent) {
    if (SHOW_PLAYBACKFRAGMENT_ON_STARTUP.equals(intent.getAction())) {
        // if this Activity is being shown after the user clicked the notification
        if (mSlidingUpPanelLayout != null) {
            mSlidingUpPanelLayout.expandPanel();
        }/*  w w w .  j  a v  a2  s. com*/
    }
    if (intent.hasExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE)) {
        Bundle bundle = new Bundle();
        bundle.putInt(TomahawkFragment.CONTENT_HEADER_MODE, ContentHeaderFragment.MODE_HEADER_STATIC_SMALL);
        FragmentUtils.replace(this, PreferencePagerFragment.class, bundle);
    }

    if (intent.getData() != null) {
        final Uri data = intent.getData();
        intent.setData(null);
        List<String> pathSegments = data.getPathSegments();
        String host = data.getHost();
        String scheme = data.getScheme();
        if ((scheme != null && (scheme.equals("spotify") || scheme.equals("tomahawk"))) || (host != null
                && (host.contains("spotify.com") || host.contains("hatchet.is") || host.contains("toma.hk")
                        || host.contains("beatsmusic.com") || host.contains("deezer.com")
                        || host.contains("rdio.com") || host.contains("soundcloud.com")))) {
            PipeLine.get().lookupUrl(data.toString());
        } else if ((pathSegments != null && pathSegments.get(pathSegments.size() - 1).endsWith(".xspf"))
                || (intent.getType() != null && intent.getType().equals("application/xspf+xml"))) {
            TomahawkRunnable r = new TomahawkRunnable(TomahawkRunnable.PRIORITY_IS_INFOSYSTEM_HIGH) {
                @Override
                public void run() {
                    Playlist pl = XspfParser.parse(data);
                    if (pl != null) {
                        final Bundle bundle = new Bundle();
                        bundle.putString(TomahawkFragment.PLAYLIST, pl.getCacheKey());
                        bundle.putInt(TomahawkFragment.CONTENT_HEADER_MODE,
                                ContentHeaderFragment.MODE_HEADER_DYNAMIC);
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                FragmentUtils.replace(TomahawkMainActivity.this, PlaylistEntriesFragment.class,
                                        bundle);
                            }
                        });
                    }
                }
            };
            ThreadManager.get().execute(r);
        } else if (pathSegments != null && (pathSegments.get(pathSegments.size() - 1).endsWith(".axe")
                || pathSegments.get(pathSegments.size() - 1).endsWith(".AXE"))) {
            InstallPluginConfigDialog dialog = new InstallPluginConfigDialog();
            Bundle args = new Bundle();
            args.putString(InstallPluginConfigDialog.PATH_TO_AXE_URI_STRING, data.toString());
            dialog.setArguments(args);
            dialog.show(getSupportFragmentManager(), null);
        } else {
            String albumName;
            String trackName;
            String artistName;
            try {
                MediaMetadataRetriever retriever = new MediaMetadataRetriever();
                retriever.setDataSource(this, data);
                albumName = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUM);
                artistName = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST);
                trackName = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE);
                retriever.release();
            } catch (Exception e) {
                Log.e(TAG, "handleIntent: " + e.getClass() + ": " + e.getLocalizedMessage());
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        String msg = TomahawkApp.getContext().getString(R.string.invalid_file);
                        Toast.makeText(TomahawkApp.getContext(), msg, Toast.LENGTH_LONG).show();
                    }
                });
                return;
            }
            if (TextUtils.isEmpty(trackName) && pathSegments != null) {
                trackName = pathSegments.get(pathSegments.size() - 1);
            }
            Query query = Query.get(trackName, albumName, artistName, false);
            Result result = Result.get(data.toString(), query.getBasicTrack(),
                    UserCollectionStubResolver.get());
            float trackScore = query.howSimilar(result);
            query.addTrackResult(result, trackScore);
            Bundle bundle = new Bundle();
            List<Query> queries = new ArrayList<>();
            queries.add(query);
            Playlist playlist = Playlist.fromQueryList(TomahawkMainActivity.getSessionUniqueStringId(), false,
                    "", "", queries);
            bundle.putString(TomahawkFragment.PLAYLIST, playlist.getCacheKey());
            bundle.putInt(TomahawkFragment.CONTENT_HEADER_MODE, ContentHeaderFragment.MODE_HEADER_DYNAMIC);
            FragmentUtils.replace(TomahawkMainActivity.this, PlaylistEntriesFragment.class, bundle);
        }
    }
}

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

@SuppressLint("NewApi")
public void play() {
    if (playList != null && currSongNumber >= 0) {
        shouldAdvance = false;/*from   w  ww  .j a  va2s.c o  m*/
        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;//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()));

    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);
}