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(Context context, Uri uri) throws IllegalArgumentException, SecurityException 

Source Link

Document

Sets the data source as a content Uri.

Usage

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;//  w  w  w  . j  ava 2s  .  c  o m
}

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

public void onSaveClicked() {
    if (mOnTrimVideoListener != null && !mOnTrimVideoListener.shouldTrim()) {
        onTrimFinished();//  w ww  .  j  a  v  a 2s . c  o m
        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);//w ww .j a va 2s .  c o 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.keylesspalace.tusky.activity.ComposeActivity.java

private void pickMedia(Uri uri, long mediaSize) {
    ContentResolver contentResolver = getContentResolver();
    if (mediaSize == MEDIA_SIZE_UNKNOWN) {
        displayTransientError(R.string.error_media_upload_opening);
        return;/*  w ww  . j  av  a  2s. c om*/
    }
    String mimeType = contentResolver.getType(uri);
    if (mimeType != null) {
        String topLevelType = mimeType.substring(0, mimeType.indexOf('/'));
        switch (topLevelType) {
        case "video": {
            if (mediaSize > STATUS_MEDIA_SIZE_LIMIT) {
                displayTransientError(R.string.error_media_upload_size);
                return;
            }
            if (mediaQueued.size() > 0 && mediaQueued.get(0).type == QueuedMedia.Type.IMAGE) {
                displayTransientError(R.string.error_media_upload_image_or_video);
                return;
            }
            MediaMetadataRetriever retriever = new MediaMetadataRetriever();
            retriever.setDataSource(this, uri);
            Bitmap source = retriever.getFrameAtTime();
            Bitmap bitmap = ThumbnailUtils.extractThumbnail(source, 128, 128);
            source.recycle();
            addMediaToQueue(QueuedMedia.Type.VIDEO, bitmap, uri, mediaSize);
            break;
        }
        case "image": {
            InputStream stream;
            try {
                stream = contentResolver.openInputStream(uri);
            } catch (FileNotFoundException e) {
                displayTransientError(R.string.error_media_upload_opening);
                return;
            }
            Bitmap source = BitmapFactory.decodeStream(stream);
            Bitmap bitmap = ThumbnailUtils.extractThumbnail(source, 128, 128);
            source.recycle();
            try {
                if (stream != null) {
                    stream.close();
                }
            } catch (IOException e) {
                bitmap.recycle();
                displayTransientError(R.string.error_media_upload_opening);
                return;
            }
            addMediaToQueue(QueuedMedia.Type.IMAGE, bitmap, uri, mediaSize);
            break;
        }
        default: {
            displayTransientError(R.string.error_media_upload_type);
            break;
        }
        }
    } else {
        displayTransientError(R.string.error_media_upload_type);
    }
}

From source file:com.fa.mastodon.activity.ComposeActivity.java

private void pickMedia(Uri uri, long mediaSize) {
    ContentResolver contentResolver = getContentResolver();
    if (mediaSize == MEDIA_SIZE_UNKNOWN) {
        displayTransientError(R.string.error_media_upload_opening);
        return;//  w ww .ja v a  2  s.c o m
    }
    String mimeType = contentResolver.getType(uri);
    if (mimeType != null) {
        String topLevelType = mimeType.substring(0, mimeType.indexOf('/'));
        switch (topLevelType) {
        case "video": {
            if (mediaSize > STATUS_MEDIA_SIZE_LIMIT) {
                displayTransientError(R.string.error_media_upload_size);
                return;
            }
            if (mediaQueued.size() > 0 && mediaQueued.get(0).type == QueuedMedia.Type.IMAGE) {
                displayTransientError(R.string.error_media_upload_image_or_video);
                return;
            }
            MediaMetadataRetriever retriever = new MediaMetadataRetriever();
            retriever.setDataSource(this, uri);
            Bitmap source = retriever.getFrameAtTime();
            Bitmap bitmap = ThumbnailUtils.extractThumbnail(source, THUMBNAIL_SIZE, THUMBNAIL_SIZE);
            source.recycle();
            addMediaToQueue(QueuedMedia.Type.VIDEO, bitmap, uri, mediaSize);
            break;
        }
        case "image": {
            InputStream stream;
            try {
                stream = contentResolver.openInputStream(uri);
            } catch (FileNotFoundException e) {
                displayTransientError(R.string.error_media_upload_opening);
                return;
            }

            Bitmap source = BitmapFactory.decodeStream(stream);
            Bitmap bitmap = ThumbnailUtils.extractThumbnail(source, THUMBNAIL_SIZE, THUMBNAIL_SIZE);
            source.recycle();
            try {
                if (stream != null) {
                    stream.close();
                }
            } catch (IOException e) {
                bitmap.recycle();
                displayTransientError(R.string.error_media_upload_opening);
                return;
            }
            addMediaToQueue(QueuedMedia.Type.IMAGE, bitmap, uri, mediaSize);
            break;
        }
        default: {
            displayTransientError(R.string.error_media_upload_type);
            break;
        }
        }
    } else {
        displayTransientError(R.string.error_media_upload_type);
    }
}

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 . ja  v  a2s  .  co m
    }
    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);
        }
    }
}