問題描述
Android MediaMetadataRetriever setDataSource 失敗 (Android MediaMetadataRetriever setDataSource failed)
I'm trying to use Android MediaMetadataRetriever
to get the length of recorded videos in mp4 format ‑ but I'm getting the exception:
07‑13 13:54:32.686: E/AndroidRuntime(19790): FATAL EXCEPTION: main
07‑13 13:54:32.686: E/AndroidRuntime(19790): java.lang.RuntimeException: setDataSource failed: status = 0x80000000
My code is:
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
retriever.setDataSource(video.getMediaUrl());
String time = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
long timeInmillisec = Long.parseLong(time);
And the video.getMediaUrl()
path is similar to this:
file:///storage/emulated/0/Foldername/Videos/VID_20130713_135318.mp4
I don't know what i am doing wrong ‑ anyone help me out, please! Also this code works fine for Audio Files, but not for videos.
參考解法
方法 1:
public static String getFileDuration(Context context, File file) {
String result = null;
MediaMetadataRetriever retriever = null;
FileInputStream inputStream = null;
try {
retriever = new MediaMetadataRetriever();
inputStream = new FileInputStream(file.getAbsolutePath());
retriever.setDataSource(inputStream.getFD());
long time = Long.parseLong(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION));
result = String.format(context.getResources().getString(R.string.player_time_format),
AppUtil.getPlayerMinutes(time), AppUtil.getPlayerSoconds(time));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (RuntimeException e) {
e.printStackTrace();
} finally{
if (retriever != null){
retriever.release()
}if (inputStream != null){
inputStream.close()
}
}
return result;
}
方法 2:
Remove file:// from video URI before passing it to setDataSource method.
方法 3:
FileInputStream works for me.
String path = "somepath"; java.io.FileInputStream input = new FileInputStream(path); mediaMetadataRetriever.setDataSource(input.getFD());
(by Lukas Olsen、Khairul Alam Licon、Kirill Feoktistov、Leandro Cadete)