Java Code Examples for android.media.MediaMetadataRetriever#extractMetadata()

The following examples show how to use android.media.MediaMetadataRetriever#extractMetadata() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: VideoCaptureIntentTest.java    From Camera2 with Apache License 2.0 6 votes vote down vote up
private int verify(CameraActivity activity, Uri uri) throws Exception
{
    assertTrue(activity.isFinishing());
    assertEquals(Activity.RESULT_OK, activity.getResultCode());

    // Verify the video file
    MediaMetadataRetriever retriever = new MediaMetadataRetriever();
    retriever.setDataSource(activity, uri);
    String duration = retriever.extractMetadata(
            MediaMetadataRetriever.METADATA_KEY_DURATION);
    assertNotNull(duration);
    int durationValue = Integer.parseInt(duration);
    Log.v(TAG, "Video duration is " + durationValue);
    assertTrue(durationValue > 0);
    return durationValue;
}
 
Example 2
Source File: AndroidFileMetaAccessor.java    From java-unified-sdk with Apache License 2.0 6 votes vote down vote up
public Map<String, Object> mediaInfo(File file) {
  Map<String, Object> meta = new HashMap<String, Object>();

  try {
    MediaMetadataRetriever retriever = new MediaMetadataRetriever();
    retriever.setDataSource(file.getAbsolutePath());

    String durationString = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
    String format = getMimeType(file.getAbsolutePath());
    double duration = Long.parseLong(durationString) / 1000.0d;

    meta.put(AVIMFileMessage.FORMAT, format);
    meta.put(AVIMFileMessage.DURATION, duration);
  } catch (Exception e) {
    meta.put(AVIMFileMessage.DURATION, 0l);
    meta.put(AVIMFileMessage.FORMAT, "");
  }

  return meta;
}
 
Example 3
Source File: UploadVideoActivity.java    From patrol-android with GNU General Public License v3.0 6 votes vote down vote up
private boolean checkIsHaveMetaData(Uri fileUri) {
    try {
        MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
        metadataRetriever.setDataSource(this, fileUri);

        contentData = metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DATE);
        contentLocation = metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_LOCATION);
        metadataRetriever.release();

        parsMetaLocation();

        SimpleDateFormat metaDateFormat = new SimpleDateFormat(Constants.VIDEO_META_DATE_MASK);
        violationDate = metaDateFormat.parse(contentData);
        return true;

    } catch (Exception e) {
        e.printStackTrace();
        contentNotReady();
        return false;
    }
}
 
Example 4
Source File: AndroidUtils.java    From iGap-Android with GNU Affero General Public License v3.0 6 votes vote down vote up
public static long getAudioDuration(Context context, String filePath) throws IllegalArgumentException {

        if (filePath == null || filePath.length() == 0) {
            return 1;
        }

        Uri uri;
        File file = new File(filePath);

        if (file.exists()) {
            uri = Uri.fromFile(file);

            try {
                MediaMetadataRetriever mmr = new MediaMetadataRetriever();
                mmr.setDataSource(context, uri);
                String durationStr = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
                return Integer.parseInt(durationStr);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return 1;
    }
 
Example 5
Source File: ExtractPicturesWorker.java    From GifAssistant with Apache License 2.0 6 votes vote down vote up
public static Bitmap extractBitmap(String videoPath, int second) {
	if (TextUtils.isEmpty(videoPath)) {
		logd("extractBitmap empty video path");
		return null;
	}

	MediaMetadataRetriever retriever = new MediaMetadataRetriever();
	retriever.setDataSource(videoPath);
	// 取得视频的长度(单位为毫秒)
	String time = retriever
			.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
	// 取得视频的长度(单位为秒)
	int total = Integer.valueOf(time) / 1000;

	if (second < 0 || second > total) {
		loge("unavalible second(" + second + "), total(" + total + ")");
		return null;
	}

	Bitmap bitmap = retriever.getFrameAtTime(second * 1000 * 1000,
			MediaMetadataRetriever.OPTION_CLOSEST_SYNC);

	return bitmap;
}
 
Example 6
Source File: MaskProgressLayout.java    From AlbumCameraRecorder with MIT License 6 votes vote down vote up
@Override
public void addAudioCover(String file) {
    MediaMetadataRetriever mmr = new MediaMetadataRetriever();
    mmr.setDataSource(file);

    String duration = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION); // ms,时长


    MultiMediaView multiMediaView = new MultiMediaView(MultimediaTypes.AUDIO);
    multiMediaView.setPath(file);
    multiMediaView.setViewHolder(this);

    // 显示音频播放控件,当点击播放的时候,才正式下载并且进行播放
    mViewHolder.playView.setVisibility(View.VISIBLE);
    isShowRemovceRecorder();
    RecordingItem recordingItem = new RecordingItem();
    recordingItem.setFilePath(file);
    recordingItem.setLength(Integer.valueOf(duration));
    mViewHolder.playView.setData(recordingItem, audioProgressColor);
}
 
Example 7
Source File: BitmapUtil.java    From videocreator with Apache License 2.0 6 votes vote down vote up
private static int[] getVideoSize(String path) {

        MediaMetadataRetriever mmr = new MediaMetadataRetriever();
        int[] size = {-1, -1};

        try {
            mmr.setDataSource(path);
//			String duration = mmr.extractMetadata(android.media.MediaMetadataRetriever.METADATA_KEY_DURATION);
            String width = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);
            String height = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);

            size[0] = Integer.parseInt(width);
            size[1] = Integer.parseInt(height);
        } catch (Exception ex) {
            Log.e(TAG, "MediaMetadataRetriever exception " + ex);
        } finally {
            mmr.release();
        }
        return size;
    }
 
Example 8
Source File: FileCreator.java    From Saiy-PS with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Used to get information about the written file
 */
private void getFileMeta() {

    if (absolutePath != null) {

        try {

            final MediaMetadataRetriever mmr = new MediaMetadataRetriever();
            mmr.setDataSource(absolutePath);
            final String duration = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
            mmr.release();

            if (DEBUG) {
                MyLog.i(CLS_NAME, "recording duration: " + duration);
            }

        } catch (final RuntimeException e) {
            if (DEBUG) {
                MyLog.w(CLS_NAME, "RuntimeException: completeFileWrite");
                e.printStackTrace();
            }
        }
    }
}
 
Example 9
Source File: VideoInfo.java    From Android-Video-Trimmer with Apache License 2.0 5 votes vote down vote up
public VideoInfo calcDuration() {
    MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
    try {
        mediaMetadataRetriever.setDataSource(getVideoPath());
        String time = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
        duration = Long.parseLong(time);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return this;
}
 
Example 10
Source File: VideoRotationMetadataLoader.java    From Camera2 with Apache License 2.0 5 votes vote down vote up
static boolean loadRotationMetadata(final FilmstripItem data)
{
    final String path = data.getData().getFilePath();
    MediaMetadataRetriever retriever = new MediaMetadataRetriever();
    try
    {
        retriever.setDataSource(path);
        data.getMetadata().setVideoOrientation(retriever.extractMetadata(
                MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION));

        String val = retriever.extractMetadata(
                MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);

        data.getMetadata().setVideoWidth(Integer.parseInt(val));

        val = retriever.extractMetadata(
                MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);

        data.getMetadata().setVideoHeight(Integer.parseInt(val));
    } catch (RuntimeException ex)
    {
        // setDataSource() can cause RuntimeException beyond
        // IllegalArgumentException. e.g: data contain *.avi file.
        Log.e(TAG, "MediaMetdataRetriever.setDataSource() fail", ex);
    }
    return true;
}
 
Example 11
Source File: MessageUtils.java    From imsdk-android with MIT License 5 votes vote down vote up
/**
 * 获取视频文件的基本信息
 *
 * @param fileName
 * @return
 */
public static VideoMessageResult getBasicVideoInfo(String fileName) {
    VideoMessageResult videoMessageResult = new VideoMessageResult();
    MediaMetadataRetriever retriever = new MediaMetadataRetriever();
    retriever.setDataSource(fileName);
    String time = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
    long timeInmillisec = Long.parseLong(time);
    long duration = timeInmillisec / 1000;
    videoMessageResult.Duration = duration + "";
    videoMessageResult.Width = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);
    videoMessageResult.Height = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);
    videoMessageResult.FileSize = FileUtils.getFormatFileSize(fileName);
    return videoMessageResult;
}
 
Example 12
Source File: VideoTimelineView.java    From TelePlus-Android with GNU General Public License v2.0 5 votes vote down vote up
public void setVideoPath(String path) {
    destroy();
    mediaMetadataRetriever = new MediaMetadataRetriever();
    progressLeft = 0.0f;
    progressRight = 1.0f;
    try {
        mediaMetadataRetriever.setDataSource(path);
        String duration = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
        videoLength = Long.parseLong(duration);
    } catch (Exception e) {
        FileLog.e(e);
    }
    invalidate();
}
 
Example 13
Source File: VideoTimelinePlayView.java    From Telegram-FOSS with GNU General Public License v2.0 5 votes vote down vote up
public void setVideoPath(String path, float left, float right) {
    destroy();
    mediaMetadataRetriever = new MediaMetadataRetriever();
    progressLeft = left;
    progressRight = right;
    try {
        mediaMetadataRetriever.setDataSource(path);
        String duration = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
        videoLength = Long.parseLong(duration);
    } catch (Exception e) {
        FileLog.e(e);
    }
    invalidate();
}
 
Example 14
Source File: OPlaylistFragment.java    From YTPlayer with GNU General Public License v3.0 4 votes vote down vote up
@Override
protected Void doInBackground(Void... voids) {
    publishProgress("Working...","(0/0)");
    File[] files = new File(ofModel.getPath()).listFiles(new FileFilter() {
        @Override
        public boolean accept(File file)
        {
            return (file.getPath().endsWith(".mp3")||file.getPath().endsWith(".m4a")
                    ||file.getPath().endsWith(".wav")||file.getPath().endsWith(".aac")
                    ||file.getPath().endsWith(".ogg")||file.getPath().endsWith(".flac"));
        }
    });
    int i=1;
    for (File f : files) {
        Uri uri = Uri.fromFile(f);
        publishProgress(f.getPath(),"("+i+"/"+files.length+")");
        try {
            MediaMetadataRetriever mmr = new MediaMetadataRetriever();
            mmr.setDataSource(activity,uri);
            String durationStr = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
            String artist = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST);
            String album = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUM);

            if (artist==null) artist ="Unknown artist";
            if (album==null) album = "Unknown album";

            int s = Integer.parseInt(durationStr)/1000;
            if (artist.contains("|"))
                artist = artist.replace("|","");
            if (album.contains("|")) album = album.replace("|","");
            builder.append("\n").append(f.getPath().trim()).append("|").append(artist.trim()).append("|")
                    .append(album.trim()).append("|").append(s).append("|").append(YTutils.getDate(new Date(f.lastModified())));
        }catch (Exception e) {
            Log.e(TAG, "searchRecursive: "+uri.toString());
        }
        i++;
    }
  //  File f = new File(activity.getFilesDir(),mainFile.getPath().replace("/","_")+".csv");
    Log.e(TAG, "FileToSave: "+mainFile.getPath());
    YTutils.writeContent(activity,mainFile.getPath(),builder.toString());
    return null;
}
 
Example 15
Source File: EasyPhotosActivity.java    From imsdk-android with MIT License 4 votes vote down vote up
private void onResult(File file) {
        boolean isVideo;
        int outWidth;
        int outHeight;
        String outMimeType;
        try {
            MediaMetadataRetriever mmr = new MediaMetadataRetriever();
            mmr.setDataSource(file.getAbsolutePath());
            outMimeType = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_MIMETYPE);
            outWidth = Integer.parseInt(mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH));
            outHeight = Integer.parseInt(mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT));
            isVideo = true;
        } catch (Exception e) {
            e.printStackTrace();
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(file.getAbsolutePath(), options);
            outMimeType = options.outMimeType;
            outWidth = options.outWidth;
            outHeight = options.outHeight;
            isVideo = false;
        }
        //if (code == Code.REQUEST_CAMERA) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HH:mm:ss", Locale.getDefault());
        String fileName = file.getName();
        String suffix = fileName.substring(fileName.lastIndexOf("."));

        String imageName;
        if (isVideo) {
            imageName = "VIDEO_%s" + suffix;
        } else {
            imageName = "IMG_%s" + suffix;
        }

        String filename = String.format(imageName, dateFormat.format(new Date()));
        File reNameFile = new File(file.getParentFile(), filename);
        if (!reNameFile.exists()) {
            if (file.renameTo(reNameFile)) {
                file = reNameFile;
            }
        }
        //}

        Photo photo = new Photo(file.getName(), file.getAbsolutePath(), file.lastModified() / 1000, outWidth, outHeight, file.length(), DurationUtils.getDuration(file.getAbsolutePath()), outMimeType);

        if (Setting.onlyStartCamera || albumModel.getAlbumItems().isEmpty()) {
            MediaScannerConnectionUtils.refresh(this, file);// 更新媒体库

            photo.selectedOriginal = Setting.selectedOriginal;
            Result.addPhoto(photo);
            done();

//            Intent data = new Intent();

//            resultList.add(photo);
//
//            data.putParcelableArrayListExtra(EasyPhotos.RESULT_PHOTOS, resultList);
//
//            data.putExtra(EasyPhotos.RESULT_SELECTED_ORIGINAL, Setting.selectedOriginal);
//
//            ArrayList<String> pathList = new ArrayList<>();
//            pathList.add(photo.path);
//
//            data.putStringArrayListExtra(EasyPhotos.RESULT_PATHS, pathList);
//
//            if (Setting.isCrop) {
//                startCrop(this, file.getAbsolutePath(), data);
//            } else {
//                setResult(RESULT_OK, data);
//                finish();
//            }
            return;
        }
        addNewPhoto(photo);
    }
 
Example 16
Source File: FileTools.java    From AndroidDownload with Apache License 2.0 4 votes vote down vote up
public static int getVideoDuration(String path){
    MediaMetadataRetriever media=new MediaMetadataRetriever();
    media.setDataSource(path);
    String duration = media.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION); //
    return Integer.parseInt(duration);
}
 
Example 17
Source File: InMemoryTranscoder.java    From mollyim-android with GNU General Public License v3.0 4 votes vote down vote up
private static boolean containsLocation(MediaMetadataRetriever mediaMetadataRetriever) {
  String locationString = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_LOCATION);
  return locationString != null;
}
 
Example 18
Source File: BasicMediaPlayerTestCase_GetCurrentPositionMethod.java    From android-openslmediaplayer with Apache License 2.0 3 votes vote down vote up
private static int getActualDuration(String path) {
    MediaMetadataRetriever retriever = new MediaMetadataRetriever();

    retriever.setDataSource(path);

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

    return Integer.parseInt(durationStr);
}
 
Example 19
Source File: FileUtils.java    From explorer with Apache License 2.0 3 votes vote down vote up
public static String getArtist(File file) {

        try {

            MediaMetadataRetriever retriever = new MediaMetadataRetriever();

            retriever.setDataSource(file.getPath());

            return retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST);
        }
        catch (Exception e) {

            return null;
        }
    }
 
Example 20
Source File: FileUtils.java    From explorer with Apache License 2.0 3 votes vote down vote up
public static String getDuration(File file) {

        try {

            MediaMetadataRetriever retriever = new MediaMetadataRetriever();

            retriever.setDataSource(file.getPath());

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

            long milliseconds = Long.parseLong(duration);

            long s = milliseconds / 1000 % 60;

            long m = milliseconds / 1000 / 60 % 60;

            long h = milliseconds / 1000 / 60 / 60 % 24;

            if (h == 0) return String.format(Locale.getDefault(), "%02d:%02d", m, s);

            return String.format(Locale.getDefault(), "%02d:%02d:%02d", h, m, s);
        }
        catch (Exception e) {

            return null;
        }
    }