Example usage for android.media MediaMetadataRetriever MediaMetadataRetriever

List of usage examples for android.media MediaMetadataRetriever MediaMetadataRetriever

Introduction

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

Prototype

public MediaMetadataRetriever() 

Source Link

Usage

From source file:Main.java

public static long getVideoAssetDurationMilliSec(Context context, Uri uri) {
    MediaMetadataRetriever retriever = new MediaMetadataRetriever();
    retriever.setDataSource(context, uri);
    String time = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
    return Long.parseLong(time);
}

From source file:Main.java

@SuppressLint("NewApi")
public static Bitmap createVideoThumbnail(String filePath, int kind) {
    Bitmap bitmap = null;/* w  w w.j a v  a  2s .  c o  m*/
    if (Build.VERSION.SDK_INT < 10) {
        // This peace of code is for compatibility with android 8 and 9.
        return android.media.ThumbnailUtils.createVideoThumbnail(filePath, kind);
    }

    // MediaMetadataRetriever is not available for Android version less than 10
    // but we need to use it in order to get first frame of the video for thumbnail.
    MediaMetadataRetriever retriever = new MediaMetadataRetriever();

    try {
        retriever.setDataSource(filePath);
        bitmap = retriever.getFrameAtTime(0);
    } catch (IllegalArgumentException ex) {
        // Assume this is a corrupt video file
    } catch (RuntimeException ex) {
        // Assume this is a corrupt video file.
    } finally {
        try {
            retriever.release();
        } catch (RuntimeException ex) {
            // Ignore failures while cleaning up.
            Log.w("ThumbnailUtils", "MediaMetadataRetriever failed with exception: " + ex);
        }
    }

    if (bitmap == null)
        return null;

    if (kind == Images.Thumbnails.MINI_KIND) {
        // Scale down the bitmap if it's too large.
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        int max = Math.max(width, height);
        if (max > 512) {
            float scale = 512f / max;
            int w = Math.round(scale * width);
            int h = Math.round(scale * height);
            bitmap = Bitmap.createScaledBitmap(bitmap, w, h, true);
        }
    } else if (kind == Images.Thumbnails.MICRO_KIND) {

        bitmap = android.media.ThumbnailUtils.extractThumbnail(bitmap, TARGET_SIZE_MICRO_THUMBNAIL,
                TARGET_SIZE_MICRO_THUMBNAIL, OPTIONS_RECYCLE_INPUT);
    }

    return bitmap;
}

From source file:jp.seikeidenron.androidtv.common.Utils.java

public static long getDuration(String videoUrl) {
    MediaMetadataRetriever mmr = new MediaMetadataRetriever();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
        mmr.setDataSource(videoUrl, new HashMap<String, String>());
    } else {//from  ww w .j av  a2  s. co m
        mmr.setDataSource(videoUrl);
    }
    return Long.parseLong(mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION));
}

From source file:avreye.mytarotadvisor.utils.Util.java

public static Bitmap getThumbnailfromVideoURL(String videoPath) throws Throwable {
    Bitmap bitmap = null;//w w  w  .  ja  v a2  s.c  om

    MediaMetadataRetriever mediaMetadataRetriever = null;
    try {
        mediaMetadataRetriever = new MediaMetadataRetriever();
        if (Build.VERSION.SDK_INT >= 14)
            mediaMetadataRetriever.setDataSource(videoPath, new HashMap<String, String>());
        else
            mediaMetadataRetriever.setDataSource(videoPath);
        //   mediaMetadataRetriever.setDataSource(videoPath);
        bitmap = mediaMetadataRetriever.getFrameAtTime(100);
    } catch (Exception e) {

        e.printStackTrace();
        throw new Throwable("Exception in retriveVideoFrameFromVideo(String videoPath)" + e.getMessage());

    } finally {
        if (mediaMetadataRetriever != null) {
            mediaMetadataRetriever.release();
        }
    }
    return bitmap;
}

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

/**
 * Take snapshots of a video file/*from   w  ww. j  a v a  2 s.  c  om*/
 *
 * @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:com.aimfire.gallery.service.MovieProcessor.java

@Override
protected void onHandleIntent(Intent intent) {
    /*//from w  ww. ja  v  a 2  s .c  o m
     * Obtain the FirebaseAnalytics instance.
     */
    mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);

    boolean[] result = new boolean[] { false, false };
    String previewPath = null;
    String thumbPath = null;
    String configPath = null;
    String convertFilePath = null;

    String exportL = MainConsts.MEDIA_3D_RAW_PATH + "L.png";
    String exportR = MainConsts.MEDIA_3D_RAW_PATH + "R.png";

    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);

    Bundle extras = intent.getExtras();
    if (extras == null) {
        if (BuildConfig.DEBUG)
            Log.e(TAG, "onHandleIntent: error, wrong parameter");
        FirebaseCrash.report(new Exception("onHandleIntent: error, wrong parameter"));
        return;
    }

    String filePathL = extras.getString("lname");
    String filePathR = extras.getString("rname");
    String cvrNameNoExt = MediaScanner.getProcessedCvrName((new File(filePathL)).getName());

    if (BuildConfig.DEBUG)
        Log.d(TAG, "onHandleIntent:left file=" + filePathL + ", right file=" + filePathR);

    String creatorName = extras.getString("creator");
    String creatorPhotoUrl = extras.getString("photo");

    float scale = extras.getFloat(MainConsts.EXTRA_SCALE);

    /*
     * if left/right videos were taken using front facing camera,
     * they need to be swapped when generating sbs 
     */
    int facing = extras.getInt(MainConsts.EXTRA_FACING);
    boolean isFrontCamera = (facing == Camera.CameraInfo.CAMERA_FACING_FRONT) ? true : false;

    MediaMetadataRetriever retriever = new MediaMetadataRetriever();

    Bitmap bitmapL = null;
    Bitmap bitmapR = null;

    long frameTime = FIRST_KEYFRAME_TIME_US;
    if (BuildConfig.DEBUG)
        Log.d(TAG, "extract frame from left at " + frameTime / 1000 + "ms");

    try {
        long startUs = SystemClock.elapsedRealtimeNanos() / 1000;

        FileInputStream inputStreamL = new FileInputStream(filePathL);
        retriever.setDataSource(inputStreamL.getFD());
        inputStreamL.close();

        bitmapL = retriever.getFrameAtTime(frameTime, MediaMetadataRetriever.OPTION_CLOSEST_SYNC);

        FileInputStream inputStreamR = new FileInputStream(filePathR);
        retriever.setDataSource(inputStreamR.getFD());
        inputStreamR.close();

        bitmapR = retriever.getFrameAtTime(frameTime, MediaMetadataRetriever.OPTION_CLOSEST_SYNC);

        retriever.release();

        long stopUs = SystemClock.elapsedRealtimeNanos() / 1000;
        if (BuildConfig.DEBUG)
            Log.d(TAG, "retrieving preview frames took " + (stopUs - startUs) / 1000 + "ms");

        if ((bitmapL != null) && (bitmapR != null)) {
            saveFrame(bitmapL, exportL);
            saveFrame(bitmapR, exportR);
        } else {
            reportError(MediaScanner.getProcessedCvrPath((new File(filePathL)).getName()),
                    ERROR_EXTRACT_SYNC_FRAME_ERROR);
            return;
        }

        previewPath = MainConsts.MEDIA_3D_THUMB_PATH + cvrNameNoExt + ".jpeg";

        result = p.getInstance().f1(exportL, exportR, previewPath, scale, isFrontCamera);
    } catch (Exception ex) {
        retriever.release();
        reportError(MediaScanner.getProcessedCvrPath((new File(filePathL)).getName()),
                ERROR_EXTRACT_SYNC_FRAME_EXCEPTION);
        return;
    }

    if (!result[0]) {
        reportError(MediaScanner.getProcessedCvrPath((new File(filePathL)).getName()),
                ERROR_EXTRACT_SIMILARITY_MATRIX);

        File leftFrom = (new File(filePathL));
        File rightFrom = (new File(filePathR));
        File leftExportFrom = (new File(exportL));
        File rightExportFrom = (new File(exportR));

        if (!BuildConfig.DEBUG) {
            leftFrom.delete();
            rightFrom.delete();

            leftExportFrom.delete();
            rightExportFrom.delete();
        } else {
            File leftTo = new File(MainConsts.MEDIA_3D_DEBUG_PATH + leftFrom.getName());
            File rightTo = new File(MainConsts.MEDIA_3D_DEBUG_PATH + rightFrom.getName());

            leftFrom.renameTo(leftTo);
            rightFrom.renameTo(rightTo);

            File leftExportTo = new File(MainConsts.MEDIA_3D_DEBUG_PATH + leftExportFrom.getName());
            File rightExportTo = new File(MainConsts.MEDIA_3D_DEBUG_PATH + rightExportFrom.getName());

            leftExportFrom.renameTo(leftExportTo);
            rightExportFrom.renameTo(rightExportTo);
        }
    } else {
        double[] similarityMat = p.getInstance().g();

        String configData = similarityMat[0] + " " + similarityMat[1] + " " + similarityMat[2] + " "
                + similarityMat[3] + " " + similarityMat[4] + " " + similarityMat[5];

        if (result[1]) {
            convertFilePath = filePathR;
        } else {
            convertFilePath = filePathL;
        }

        configPath = createConfigFile(convertFilePath, configData);

        /*
         * save the thumbnail
         */
        if (bitmapL != null) {
            thumbPath = MainConsts.MEDIA_3D_THUMB_PATH + cvrNameNoExt + ".jpg";
            saveThumbnail(bitmapL, thumbPath);

            MediaScanner.insertExifInfo(thumbPath, "name=" + creatorName + "photourl=" + creatorPhotoUrl);
        }

        createZipFile(filePathL, filePathR, configPath, thumbPath, previewPath);

        /*
         * let CamcorderActivity know we are done.
         */
        reportResult(MediaScanner.getProcessedCvrPath((new File(filePathL)).getName()));
    }

    /*
     * paranoia
     */
    if (bitmapL != null) {
        bitmapL.recycle();
    }
    if (bitmapR != null) {
        bitmapR.recycle();
    }

    (new File(exportL)).delete();
    (new File(exportR)).delete();
}

From source file:de.lebenshilfe_muenster.uk_gebaerden_muensterland.sign_video_view.AbstractSignVideoFragment.java

private void setVideoViewDimensionToMatchVideoMetadata(VideoView videoView, Uri uri) {
    String metadataVideoWidth;//from w w  w  . j  a v a2  s.  c  om
    String metadataVideoHeight;
    try {
        final MediaMetadataRetriever metaRetriever = new MediaMetadataRetriever();
        metaRetriever.setDataSource(getActivity(), uri);
        metadataVideoWidth = metaRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);
        metadataVideoHeight = metaRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);
        metaRetriever.release();
        Validate.notEmpty(metadataVideoWidth);
        Validate.notEmpty(metadataVideoHeight);
    } catch (NullPointerException | IllegalArgumentException ex) {
        throw new VideoSetupException(getActivity().getString(R.string.ASVF_2) + ex.getLocalizedMessage(), ex);
    }
    if (null == metadataVideoWidth) {
        throw new VideoSetupException(getActivity().getString(R.string.ASVF_3));
    }
    if (null == metadataVideoHeight) {
        throw new VideoSetupException(getActivity().getString(R.string.ASVF_4));
    }
    final double videoWidth = Double.valueOf(metadataVideoWidth);
    final double videoHeight = Double.valueOf(metadataVideoHeight);
    final double videoRatio = videoWidth / videoHeight;
    Log.d(TAG, String.format("videoWidth: %s, videoHeight: %s, videoRatio: %s", videoWidth, videoHeight,
            videoRatio));
    boolean isOrientationPortrait = Configuration.ORIENTATION_PORTRAIT == getResources()
            .getConfiguration().orientation;
    int displayHeight = getResources().getDisplayMetrics().heightPixels;
    int displayWidth = getResources().getDisplayMetrics().widthPixels;
    Log.d(TAG, String.format("displayHeight: %s, displayWidth: %s", displayHeight, displayWidth));
    final double desiredVideoWidth, desiredVideoHeight;
    if (isOrientationPortrait) {
        desiredVideoWidth = displayWidth * MAXIMUM_VIDEO_WIDTH_ON_PORTRAIT;
        desiredVideoHeight = 1 / (videoRatio / desiredVideoWidth);
        Log.d(TAG, String.format("OrientationPortrait: desiredVideoWidth: %s, desiredVideoHeight: %s",
                desiredVideoWidth, desiredVideoHeight));
    } else { // orientation is Landscape
        desiredVideoHeight = displayHeight * MAXMIMUM_VIDEO_HEIGHT_ON_LANDSCAPE;
        desiredVideoWidth = desiredVideoHeight * videoRatio;
        Log.d(TAG, String.format("OrientationLandscape: desiredVideoWidth: %s, desiredVideoHeight: %s",
                desiredVideoWidth, desiredVideoHeight));
    }
    final ViewGroup.LayoutParams layoutParams = videoView.getLayoutParams();
    layoutParams.width = (int) desiredVideoWidth;
    layoutParams.height = (int) desiredVideoHeight;
}

From source file:org.gateshipone.odyssey.utils.FileExplorerHelper.java

/**
 * create a TrackModel for the given File
 * if no entry in the mediadb is found a dummy TrackModel will be created
 *///from ww w.j av  a  2  s .  com
public TrackModel getTrackModelForFile(Context context, FileModel file) {
    TrackModel track = null;

    String urlString = file.getURLString();

    if (mTrackHash.isEmpty()) {
        // lookup the current file in the media db
        String whereVal[] = { urlString };

        String where = MediaStore.Audio.Media.DATA + "=?";

        Cursor cursor = PermissionHelper.query(context, MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                MusicLibraryHelper.projectionTracks, where, whereVal, MediaStore.Audio.Media.TRACK);

        if (cursor != null) {
            if (cursor.moveToFirst()) {
                String title = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
                long duration = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION));
                int no = cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media.TRACK));
                String artist = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
                String album = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM));
                String url = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
                String albumKey = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_KEY));
                long id = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media._ID));

                track = new TrackModel(title, artist, album, albumKey, duration, no, url, id);
            }

            cursor.close();
        }
    } else {
        // use pre built hash to lookup the file
        track = mTrackHash.get(urlString);
    }

    if (track == null) {
        // no entry in the media db was found so create a custom track
        try {
            // try to read the file metadata

            MediaMetadataRetriever retriever = new MediaMetadataRetriever();

            retriever.setDataSource(context, Uri.parse(FormatHelper.encodeFileURI(urlString)));

            String title = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE);

            if (title == null) {
                title = file.getName();
            }

            String durationString = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);

            long duration = 0;

            if (durationString != null) {
                try {
                    duration = Long.valueOf(durationString);
                } catch (NumberFormatException e) {
                    duration = 0;
                }
            }

            String noString = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_CD_TRACK_NUMBER);

            int no = -1;

            if (noString != null) {
                try {
                    if (noString.contains("/")) {
                        // if string has the format (trackNumber / numberOfTracks)
                        String[] components = noString.split("/");
                        if (components.length > 0) {
                            no = Integer.valueOf(components[0]);
                        }
                    } else {
                        no = Integer.valueOf(noString);
                    }
                } catch (NumberFormatException e) {
                    no = -1;
                }
            }

            String artist = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST);
            String album = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUM);

            String albumKey = "" + ((artist == null ? "" : artist) + (album == null ? "" : album)).hashCode();

            track = new TrackModel(title, artist, album, albumKey, duration, no, urlString, -1);
        } catch (Exception e) {
            String albumKey = "" + file.getName().hashCode();
            track = new TrackModel(file.getName(), "", "", albumKey, 0, -1, urlString, -1);
        }
    }

    return track;
}

From source file:com.example.aakas.signuptest.UploadVideo.java

@Override
protected Void doInBackground(Context... params) {
    this.context = params[0];
    Log.v("UploadVideo.java", "Here************");
    try {/*from   ww w. j  a  v a  2  s .com*/

        HttpTransport transport = new NetHttpTransport();
        JsonFactory jsonFactory = new GsonFactory();
        Log.d("UploadVideo.java", credential.getSelectedAccountName() + "!!!!!!!!!!");
        //             YouTube client

        youtube = new YouTube.Builder(transport, jsonFactory, credential).setApplicationName("Umeed 1.0")
                .build();
        Log.d("UploadVideo.java", credential.getSelectedAccountName() + "|||||||||||||||||");

        Log.v("UploadVideo.java", "0************");

        System.out.println("Uploading video");

        Video videoObjectDefiningMetadata = new Video();

        // Set the video to be publicly visible. This is the default
        // setting. Other supporting settings are "unlisted" and "private."
        VideoStatus status = new VideoStatus();
        status.setPrivacyStatus(video.getStatus());
        videoObjectDefiningMetadata.setStatus(status);

        // Most of the video's metadata is set on the VideoSnippet object.
        VideoSnippet snippet = new VideoSnippet();

        snippet.setTitle(video.getTitle());
        snippet.setDescription(video.getDescription());
        Log.v("UploadVideo.java", "1************");
        List<String> tags = new ArrayList<String>();
        snippet.setTags(video.getTags());

        videoObjectDefiningMetadata.setSnippet(snippet);
        InputStreamContent mediaContent = new InputStreamContent(VIDEO_FILE_FORMAT,
                new BufferedInputStream(new FileInputStream(video.getUri())));
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();

        YouTube.Videos.Insert videoInsert = youtube.videos().insert("snippet,statistics,status",
                videoObjectDefiningMetadata, mediaContent);
        // Set the upload type and add an event listener.
        MediaHttpUploader uploader = videoInsert.getMediaHttpUploader();
        Log.v("UploadVideo.java", "3************");

        uploader.setDirectUploadEnabled(true);

        MediaHttpUploaderProgressListener progressListener = new MediaHttpUploaderProgressListener() {
            public void progressChanged(MediaHttpUploader uploader) throws IOException {
                switch (uploader.getUploadState()) {
                case INITIATION_STARTED:
                    Log.v("UploadVideo.java", "Initiation Started");
                    break;
                case INITIATION_COMPLETE:
                    Log.v("UploadVideo.java", "Initiation Completed");
                    break;
                case MEDIA_IN_PROGRESS:
                    Log.v("UploadVideo.java", "Upload in progress");
                    Log.v("UploadVideo.java", "Upload percentage: " + uploader.getNumBytesUploaded());
                    break;
                case MEDIA_COMPLETE:
                    Log.v("UploadVideo.java", "Upload Completed!");
                    break;
                case NOT_STARTED:
                    Log.v("UploadVideo.java", "Upload Not Started!");
                    break;
                }
            }
        };
        uploader.setProgressListener(progressListener);
        Log.v("UploadVideo.java", "4************");

        // Call the API and upload the video.
        Log.d("UploadVideo.java", "*****" + credential.getSelectedAccountName() + "*****");
        Video returnedVideo = videoInsert.execute();

        // Print data about the newly inserted video from the API response.
        System.out.println("\n================== Returned Video ==================\n");
        System.out.println("  - Id: " + returnedVideo.getId());
        System.out.println("  - Title: " + returnedVideo.getSnippet().getTitle());
        System.out.println("  - Tags: " + returnedVideo.getSnippet().getTags());
        System.out.println("  - Privacy Status: " + returnedVideo.getStatus().getPrivacyStatus());
        System.out.println("  - Video Count: " + returnedVideo.getStatistics().getViewCount());
        Log.v("UploadVideo.java", "Success************");
        this.returnVideoId = returnedVideo.getId();
        activity.doSomething(this.returnVideoId);

    } catch (UserRecoverableAuthIOException userRecoverableException) {
        Log.i(TAG, String.format("UserRecoverableAuthIOException: %s",
                userRecoverableException.getMessage() + "........"));
        ((SignUpChoosingActivity) context).startActivityForResult(userRecoverableException.getIntent(),
                REQUEST_AUTHORIZATION);
        //            requestAuth(context, userRecoverableException);
    } catch (GoogleJsonResponseException e) {
        Log.v("UploadVideo.java", "5************");

        System.err.println("GoogleJsonResponseException code: " + e.getDetails().getCode() + " : "
                + e.getDetails().getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        Log.v("UploadVideo.java", "6************");
        System.err.println("IOException: " + e.getMessage());
        e.printStackTrace();
    } catch (Throwable t) {
        Log.v("UploadVideo.java", "7************");

        System.err.println("Throwable: " + t.getMessage());
        t.printStackTrace();
    }
    return null;
}

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);/*w  w w  .j  a v  a  2 s .c  o 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;
}