private Dimensions getVideoDimensions(File file) throws NotAVideoFile { MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever(); try { metadataRetriever.setDataSource(file.getAbsolutePath()); } catch (Exception e) { throw new NotAVideoFile(); } String hasVideo = metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_HAS_VIDEO); if (hasVideo == null) { throw new NotAVideoFile(); } int rotation = extractRotationFromMediaRetriever(metadataRetriever); boolean rotated = rotation == 90 || rotation == 270; int height; try { String h = metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT); height = Integer.parseInt(h); } catch (Exception e) { height = -1; } int width; try { String w = metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH); width = Integer.parseInt(w); } catch (Exception e) { width = -1; } metadataRetriever.release(); Log.d(Config.LOGTAG, "extracted video dims " + width + "x" + height); return rotated ? new Dimensions(width, height) : new Dimensions(height, width); }
protected void updateMovieInfo() { mVideoWidth = mVideoHeight = mRotation = mBitrate = 0; mDuration = 0; mFrameRate = 0; String value = mMetadata.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH); if (!TextUtils.isEmpty(value)) { mVideoWidth = Integer.parseInt(value); } value = mMetadata.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT); if (!TextUtils.isEmpty(value)) { mVideoHeight = Integer.parseInt(value); } value = mMetadata.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION); if (!TextUtils.isEmpty(value)) { mRotation = Integer.parseInt(value); } value = mMetadata.extractMetadata(MediaMetadataRetriever.METADATA_KEY_BITRATE); if (!TextUtils.isEmpty(value)) { mBitrate = Integer.parseInt(value); } value = mMetadata.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION); if (!TextUtils.isEmpty(value)) { mDuration = Long.parseLong(value) * 1000; } }
private void addSongToList(File file) { if (file.getName().endsWith(".mp3")) { DatabaseHandler db = new DatabaseHandler(Setting.this); String songName = file.getName().substring(0, (file.getName().length() - 4)); String songPath = file.getPath(); MediaMetadataRetriever media = new MediaMetadataRetriever(); media.setDataSource(songPath); byte[] data = media.getEmbeddedPicture(); String songArtist = media.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST); String songAlbum = media.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUM); media.release(); db.addSongData(new SongData(songName, songPath, songArtist, songAlbum, data, 0)); db.close(); } }
public UFile(String path) { try { file = new File(path); this.path = file.getPath(); this.name = file.getName(); size = file.length(); thumbNail = null; if (isMovie()) { MediaMetadataRetriever retriever = new MediaMetadataRetriever(); retriever.setDataSource(path); String time = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION); movieLength = Long.parseLong(time); thumbNail = ThumbnailUtils.createVideoThumbnail( path, MediaStore.Video.Thumbnails.FULL_SCREEN_KIND); } else if (isImage()) { Bitmap temp = BitmapFactory.decodeFile(file.getPath()); float scale = context.getResources().getDisplayMetrics().densityDpi / 160f; thumbNail = ThumbnailUtils.extractThumbnail(temp, (int) (50f * scale), (int) (50f * scale)); } else if (file.isDirectory()) { thumbNail = BitmapFactory.decodeResource(null, R.mipmap.docu); } } catch (Exception e) { file = null; } }
public static long getVideoDurationInMillis(String videoFile) { MediaMetadataRetriever retriever = new MediaMetadataRetriever(); retriever.setDataSource(videoFile); String time = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION); long timeInmillisec = Long.parseLong(time); retriever.release(); return timeInmillisec; }
public void setVideoPath(String path) { mediaMetadataRetriever = new MediaMetadataRetriever(); try { mediaMetadataRetriever.setDataSource(path); String duration = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION); videoLength = Long.parseLong(duration); } catch (Exception e) { FileLog.e("tmessages", e); } }
private int getDuration() { Movie movie = mItems.get(mCurrentItem); MediaMetadataRetriever mmr = new MediaMetadataRetriever(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { mmr.setDataSource(movie.getVideoUrl(), new HashMap<String, String>()); } else { mmr.setDataSource(movie.getVideoUrl()); } String time = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION); long duration = Long.parseLong(time); return (int) duration; }
// @TargetApi(11) private void calculateDuration(ContentValues map) throws IOException { if (Utils.isGingerBreadMROrLater()) { File videoFile = fileFromResourceMap(map); MediaMetadataRetriever mmr = new MediaMetadataRetriever(); mmr.setDataSource(videoFile.toString()); String duration = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION); if (!TextUtils.isEmpty(duration)) { map.put(Resources.DURATION, Integer.valueOf(duration)); } mmr.release(); } }
/** * Returns a (possibly empty) Cursor for given file path * * @param path The path to the file to be queried * @return A new Cursor object */ public static Cursor getCursorForFileQuery(String path) { MatrixCursor matrixCursor = new MatrixCursor(Song.FILLED_PROJECTION); MediaMetadataRetriever data = new MediaMetadataRetriever(); try { data.setDataSource(path); } catch (Exception e) { Log.w("VanillaMusic", "Failed to extract metadata from " + path); } String title = data.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE); String album = data.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUM); String artist = data.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST); String duration = data.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION); if (duration != null) { // looks like we will be able to play this file // Vanilla requires each file to be identified by its unique id in the media database. // However: This file is not in the database, so we are going to roll our own // using the negative crc32 sum of the path value. While this is not perfect // (the same file may be accessed using various paths) it's the fastest method // and far good enough. CRC32 crc = new CRC32(); crc.update(path.getBytes()); Long songId = (Long) (2 + crc.getValue()) * -1; // must at least be -2 (-1 defines Song-Object to be empty) // Build minimal fake-database entry for this file Object[] objData = new Object[] {songId, path, "", "", "", 0, 0, 0, 0}; if (title != null) objData[2] = title; if (album != null) objData[3] = album; if (artist != null) objData[4] = artist; if (duration != null) objData[7] = Long.parseLong(duration, 10); matrixCursor.addRow(objData); } return matrixCursor; }
// Verify result code, result data, and the duration. 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; }
public AlbumMetaData mediaMetaData(String file_path) { AlbumMetaData albumMetaData = new AlbumMetaData(); try { if (mmr == null) { mmr = new MediaMetadataRetriever(); } mmr.setDataSource(file_path); albumMetaData.file_path = file_path; albumMetaData.title = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE); albumMetaData.album_artist = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUMARTIST); albumMetaData.artist = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST); albumMetaData.author = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_AUTHOR); albumMetaData.genre = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_AUTHOR); albumMetaData.duration = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION); // albumMetaData.album_art = mmr.getEmbeddedPicture(); } catch (Exception ex) { Log.e("Error: ", "Unable to get meta data"); } if (albumMetaData.file_path == null || albumMetaData.file_path.isEmpty()) albumMetaData.file_path = ""; if (albumMetaData.album_artist == null || albumMetaData.album_artist.isEmpty()) albumMetaData.album_artist = "Unknown Album Artist"; if (albumMetaData.title == null || albumMetaData.title.isEmpty()) albumMetaData.title = "Unknown Title"; if (albumMetaData.artist == null || albumMetaData.artist.isEmpty()) albumMetaData.artist = "Unknown Artist"; if (albumMetaData.author == null || albumMetaData.author.isEmpty()) albumMetaData.author = "Unknown Author"; if (albumMetaData.genre == null || albumMetaData.genre.isEmpty()) albumMetaData.genre = "Unknown Genre"; if (albumMetaData.duration == null || albumMetaData.duration.isEmpty()) albumMetaData.duration = "-:-"; mmr.release(); return albumMetaData; }
private boolean RetrieverFile(String path, int nType) { nVideoW = 0; nVideoH = 0; // 取得影片寬高 MediaMetadataRetriever metaRetriever = new MediaMetadataRetriever(); // --20150327-fix crash bug try { metaRetriever.setDataSource(path); } catch (Exception e) { e.printStackTrace(); metaRetriever.release(); Log.v(TAG, "PATH=" + path); Log.e(TAG, "MediaMetadataRetriever setDataSource error"); return false; } // !--20150327-fix crash bug if (nType == 1) { String temp = metaRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH); if (temp != null) { try { nVideoW = Integer.parseInt(temp); } catch (Exception e) { e.printStackTrace(); } } temp = metaRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT); if (temp != null) { try { nVideoH = Integer.parseInt(temp); } catch (Exception e) { e.printStackTrace(); } } } metaRetriever.release(); return true; }
private int extractRotationFromMediaRetriever(MediaMetadataRetriever metadataRetriever) { int rotation; if (Build.VERSION.SDK_INT >= 17) { String r = metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION); try { rotation = Integer.parseInt(r); } catch (Exception e) { rotation = 0; } } else { rotation = 0; } return rotation; }
private void initMediaDuration(Uri uri) throws MmsException { if (uri == null) { throw new IllegalArgumentException("Uri may not be null."); } MediaMetadataRetriever retriever = new MediaMetadataRetriever(); int duration = 0; try { retriever.setDataSource(mContext, uri); String dur = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION); if (dur != null) { duration = Integer.parseInt(dur); } mDuration = duration; Xlog.i(TAG, "Got audio duration:" + duration); } catch (Exception ex) { Xlog.e(TAG, "MediaMetadataRetriever failed to get duration for " + uri.getPath(), ex); throw new MmsException(ex); } finally { retriever.release(); } }
public void sendVideo(Peer peer, String fullFilePath, String fileName) { try { MediaMetadataRetriever retriever = new MediaMetadataRetriever(); retriever.setDataSource(fullFilePath); int duration = (int) (Long.parseLong( retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)) / 1000L); Bitmap img = retriever.getFrameAtTime(0); int width = img.getWidth(); int height = img.getHeight(); Bitmap smallThumb = ImageHelper.scaleFit(img, 90, 90); byte[] smallThumbData = ImageHelper.save(smallThumb); FastThumb thumb = new FastThumb(smallThumb.getWidth(), smallThumb.getHeight(), smallThumbData); sendVideo(peer, fileName, width, height, duration, thumb, fullFilePath); } catch (Throwable e) { e.printStackTrace(); } }
private void CheckDir(String src) { // http://www.exampledepot.com/egs/java.io/GetFiles.html File rootNode = new File(src); boolean folderHasAlbumArt = false; try { if (rootNode.list(hasAlbumArt).length > 0) { folderHasAlbumArt = true; } for (String mp3 : rootNode.list(isMP3)) { metaDataReader.setDataSource(src + mp3); title = metaDataReader.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE); String preFormat = metaDataReader.extractMetadata(MediaMetadataRetriever.METADATA_KEY_CD_TRACK_NUMBER); String postFormat = "0"; String item; boolean passed = false; if (preFormat != null && preFormat != "") { for (int i = 0; i < preFormat.length(); i++) { item = preFormat.substring(i, i + 1); if (item != "/" && passed != true) { postFormat = postFormat + item; } else { passed = true; } } try { number = Integer.parseInt(postFormat); } catch (NumberFormatException e) { // TODO fill } } else { number = 0; } artist = metaDataReader.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST); album = metaDataReader.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUM); length = Double.parseDouble( metaDataReader.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)); if (title == null) { title = "Unknown"; } if (artist == null) { artist = "Unknown"; } if (album == null) { album = "Unknown"; } Track t = new Track(trackCount, title, number, artist, album, length, src + mp3); t.SetAlbumArt(folderHasAlbumArt); t.SetRootSrc(src); AddTrack(t); trackCount++; } for (String dir : rootNode.list(isDIR)) { CheckDir(src + dir + "/"); } } catch (NullPointerException e) { // Probably No SD-Card Log.v(preferences.GetTag(), e.getMessage()); } }
@Override public void run() { FeedMedia media = DBReader.getFeedMedia(DownloadService.this, request.getFeedfileId()); if (media == null) { throw new IllegalStateException("Could not find downloaded media object in database"); } boolean chaptersRead = false; media.setDownloaded(true); media.setFile_url(request.getDestination()); // Get duration MediaMetadataRetriever mmr = null; try { mmr = new MediaMetadataRetriever(); mmr.setDataSource(media.getFile_url()); String durationStr = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION); media.setDuration(Integer.parseInt(durationStr)); if (AppConfig.DEBUG) Log.d(TAG, "Duration of file is " + media.getDuration()); } catch (NumberFormatException e) { e.printStackTrace(); } catch (RuntimeException e) { e.printStackTrace(); } finally { if (mmr != null) { mmr.release(); } } if (media.getItem().getChapters() == null) { ChapterUtils.loadChaptersFromFileUrl(media); if (media.getItem().getChapters() != null) { chaptersRead = true; } } try { if (chaptersRead) { DBWriter.setFeedItem(DownloadService.this, media.getItem()).get(); } DBWriter.setFeedMedia(DownloadService.this, media).get(); if (!DBTasks.isInQueue(DownloadService.this, media.getItem().getId())) { DBWriter.addQueueItem(DownloadService.this, media.getItem().getId()).get(); } } catch (ExecutionException e) { e.printStackTrace(); status = new DownloadStatus( media, media.getEpisodeTitle(), DownloadError.ERROR_DB_ACCESS_ERROR, false, e.getMessage()); } catch (InterruptedException e) { e.printStackTrace(); status = new DownloadStatus( media, media.getEpisodeTitle(), DownloadError.ERROR_DB_ACCESS_ERROR, false, e.getMessage()); } saveDownloadStatus(status); sendDownloadHandledIntent(); numberOfDownloads.decrementAndGet(); queryDownloadsAsync(); }
public void displaySongInfo(final MusicDirectory.Entry song) { Integer bitrate = null; String format = null; long size = 0; try { DownloadFile downloadFile = new DownloadFile(SubsonicTabActivity.this, song, false); File file = downloadFile.getCompleteFile(); if (file.exists()) { MediaMetadataRetriever metadata = new MediaMetadataRetriever(); metadata.setDataSource(file.getAbsolutePath()); String tmp = metadata.extractMetadata(MediaMetadataRetriever.METADATA_KEY_BITRATE); bitrate = Integer.parseInt((tmp != null) ? tmp : "0") / 1000; format = FileUtil.getExtension(file.getName()); size = file.length(); if (Util.isOffline(SubsonicTabActivity.this)) { 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"); } String msg = ""; if (!song.isVideo()) { msg += "Artist: " + song.getArtist() + "\nAlbum: " + song.getAlbum(); } if (song.getTrack() != null && song.getTrack() != 0) { msg += "\nTrack: " + song.getTrack(); } if (song.getGenre() != null && !"".equals(song.getGenre())) { msg += "\nGenre: " + song.getGenre(); } if (song.getYear() != null && song.getYear() != 0) { msg += "\nYear: " + song.getYear(); } if (!Util.isOffline(SubsonicTabActivity.this)) { msg += "\nServer Format: " + song.getSuffix(); if (song.getBitRate() != null && song.getBitRate() != 0) { msg += "\nServer Bitrate: " + song.getBitRate() + " kpbs"; } } if (format != null && !"".equals(format)) { msg += "\nCached Format: " + format; } if (bitrate != null && bitrate != 0) { msg += "\nCached Bitrate: " + bitrate + " kpbs"; } if (size != 0) { msg += "\nSize: " + Util.formatBytes(size); } if (song.getDuration() != null && song.getDuration() != 0) { msg += "\nLength: " + Util.formatDuration(song.getDuration()); } new AlertDialog.Builder(this) .setIcon(android.R.drawable.ic_dialog_alert) .setTitle(song.getTitle()) .setMessage(msg) .show(); }