Android获取视频时长、宽、高等属性信息代码示例:
方式一
var width = 0 //宽
var height = 0 //高
var duration = 0L //时长(单位毫秒)
try {
val mediaMetadata = MediaMetadataRetriever()
mediaMetadata.setDataSource(file.path)
width = mediaMetadata.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH)?.toIntOrNull()?:0
height = mediaMetadata.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT)?.toIntOrNull()?:0
duration = mediaMetadata.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)?.toLongOrNull()?:0L
} catch (e: Exception) {
e.printStackTrace()
}
if (width == 0 || height == 0 || duration <= 0) {
//获取失败
}
方式二
try {
var width = 0 //宽
var height = 0 //高
var duration = 0L //时长(单位微秒)
val path = file.path //文件路径(file-path or http URL)
val mediaExtractor = MediaExtractor()
mediaExtractor.setDataSource(path)
var videoTrack = -1
val numTracks = mediaExtractor.trackCount
for (i in 0 until numTracks) {
val format = mediaExtractor.getTrackFormat(i)
val mime = format.getString(MediaFormat.KEY_MIME)
if (mime?.startsWith("video/") == true) {
videoTrack = i
break
}
}
if (videoTrack == -1) {
throw RuntimeException("未发现视频轨道")
}
val mediaFormat = mediaExtractor.getTrackFormat(videoTrack)
duration = if (mediaFormat.containsKey(MediaFormat.KEY_DURATION)) mediaFormat.getLong(
MediaFormat.KEY_DURATION
) else 0L //时长
width = if (mediaFormat.containsKey(MediaFormat.KEY_WIDTH)) mediaFormat.getInteger(
MediaFormat.KEY_WIDTH
) else 0
height = if (mediaFormat.containsKey(MediaFormat.KEY_HEIGHT)) mediaFormat.getInteger(
MediaFormat.KEY_HEIGHT
) else 0
mediaExtractor.release()
} catch (e: Exception) {
e.printStackTrace()
}
常见的属性还有:
比特率:MediaFormat.KEY_BIT_RATE
帧率:MediaFormat.KEY_FRAME_RATE
MIME:MediaFormat.KEY_MIME
其他属性参考 MediaFormat.KEY_**
网友评论