2014-01-17 19 views
0

我想獲得媒體文件的持續時間。使用MediaMetadataRetriever時如何區分文件無效?

我使用MediaMetadataRetriever來獲取媒體文件的持續時間,如下面的代碼。

File file = new File(viewTag.mFileNode.mName) ; 
        String tempfilePath = file.getPath(); 
        MediaMetadataRetriever fileDuration = new MediaMetadataRetriever(); 

        fileDuration.setDataSource(tempfilePath); 

        duration = fileDuration.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION); 
        Log.i(TAG, "duration = " + duration); 

        Long VideoDuration = Long.parseLong(duration); 
        Long minius = (VideoDuration/1000)/60; 
        Long seconds = (VideoDuration/1000) % 60; 

        viewTag.mTime.setText(String.valueOf(minius) + ":" + String.valueOf(seconds)) ; 

它工作時,媒體文件是正常的,但它在fileDuration.setDataSource(tempfilePath);崩潰時,媒體文件損壞。

如何避免媒體文件損壞時的崩潰?

我的想法是:

If(the media is normal){ 

    //Use MediaMetadataRetriever to get the duration of file 

}else if(the media file is damage) { 

    //doesn't Use MediaMetadataRetriever to get the duration of file 

} 

使用MediaMetadataRetriever時,如何區分文件被損壞?

是否有其他方法來獲取媒體文件的持續時間?

回答

0

爲什麼不能用下面的辦法:

File file = new File(viewTag.mFileNode.mName) ; 
String tempfilePath = file.getPath(); 
MediaMetadataRetriever fileDuration = new MediaMetadataRetriever(); 

try { 
    fileDuration.setDataSource(tempfilePath); 

    duration = fileDuration.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION); 
    Log.i(TAG, "duration = " + duration); 

    Long VideoDuration = Long.parseLong(duration); 
    Long minius = (VideoDuration/1000)/60; 
    Long seconds = (VideoDuration/1000) % 60; 

    viewTag.mTime.setText(String.valueOf(minius) + ":" + String.valueOf(seconds)) ; 
} catch (Exception ex) { 
    // the file must be corrupt, do something else... 
} finally { 
    // call release when you are done! 
    fileDuration.release(); 
} 

FFmpegMediaMetadataRetriever也有損壞的文件效果很好。你也可以試試這個庫。

+0

它似乎解決了這個問題,但我可以問爲什麼? – Martin

+0

該庫使用FFmpeg,它可以更好地處理損壞的文件。如果它解決了你的問題,你能接受這個答案嗎? –