Android音视频开发 - MediaMetadataRetriever 相关

Android音视频开发 - MediaMetadataRetriever 相关

MediaMetadataRetriever 是android中用于从媒体文件中提取元数据新的类. 可以获取音频,视频和图像文件的各种信息,如时长,标题,封面等.

1:初始化对象

private MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
mediaMetadataRetriever.setDataSource("sdcard/share.mp4");

需要申请读写权限.

这里我使用的是本地路径, 需要注意的是如果路径文件不存在,会抛出

IllegalArgumentException,具体的源码如下:

public void setDataSource(String path) throws IllegalArgumentException {if (path == null) {throw new IllegalArgumentException();}try (FileInputStream is = new FileInputStream(path)) {FileDescriptor fd = is.getFD();setDataSource(fd, 0, 0x7ffffffffffffffL);} catch (FileNotFoundException fileEx) {throw new IllegalArgumentException();} catch (IOException ioEx) {throw new IllegalArgumentException();}
}

2: extractMetadata

根据keyCode返回keyCode关联的元数据.

系统的keyCode如下:

 /*** The metadata key to retrieve the numeric string describing the* order of the audio data source on its original recording.*/public static final int METADATA_KEY_CD_TRACK_NUMBER = 0;/*** The metadata key to retrieve the information about the album title* of the data source.*/public static final int METADATA_KEY_ALBUM           = 1;/*** The metadata key to retrieve the information about the artist of* the data source.*/public static final int METADATA_KEY_ARTIST          = 2;/*** The metadata key to retrieve the information about the author of* the data source.*/public static final int METADATA_KEY_AUTHOR          = 3;/*** The metadata key to retrieve the information about the composer of* the data source.*/public static final int METADATA_KEY_COMPOSER        = 4;/*** The metadata key to retrieve the date when the data source was created* or modified.*/public static final int METADATA_KEY_DATE            = 5;/*** The metadata key to retrieve the content type or genre of the data* source.*/public static final int METADATA_KEY_GENRE           = 6;/*** The metadata key to retrieve the data source title.*/public static final int METADATA_KEY_TITLE           = 7;/*** The metadata key to retrieve the year when the data source was created* or modified.*/public static final int METADATA_KEY_YEAR            = 8;/*** The metadata key to retrieve the playback duration of the data source.*/public static final int METADATA_KEY_DURATION        = 9;/*** The metadata key to retrieve the number of tracks, such as audio, video,* text, in the data source, such as a mp4 or 3gpp file.*/public static final int METADATA_KEY_NUM_TRACKS      = 10;/*** The metadata key to retrieve the information of the writer (such as* lyricist) of the data source.*/public static final int METADATA_KEY_WRITER          = 11;/*** The metadata key to retrieve the mime type of the data source. Some* example mime types include: "video/mp4", "audio/mp4", "audio/amr-wb",* etc.*/public static final int METADATA_KEY_MIMETYPE        = 12;/*** The metadata key to retrieve the information about the performers or* artist associated with the data source.*/public static final int METADATA_KEY_ALBUMARTIST     = 13;/*** The metadata key to retrieve the numberic string that describes which* part of a set the audio data source comes from.*/public static final int METADATA_KEY_DISC_NUMBER     = 14;/*** The metadata key to retrieve the music album compilation status.*/public static final int METADATA_KEY_COMPILATION     = 15;/*** If this key exists the media contains audio content.*/public static final int METADATA_KEY_HAS_AUDIO       = 16;/*** If this key exists the media contains video content.*/public static final int METADATA_KEY_HAS_VIDEO       = 17;/*** If the media contains video, this key retrieves its width.*/public static final int METADATA_KEY_VIDEO_WIDTH     = 18;/*** If the media contains video, this key retrieves its height.*/public static final int METADATA_KEY_VIDEO_HEIGHT    = 19;/*** This key retrieves the average bitrate (in bits/sec), if available.*/public static final int METADATA_KEY_BITRATE         = 20;/*** This key retrieves the language code of text tracks, if available.* If multiple text tracks present, the return value will look like:* "eng:chi"* @hide*/public static final int METADATA_KEY_TIMED_TEXT_LANGUAGES      = 21;/*** If this key exists the media is drm-protected.* @hide*/public static final int METADATA_KEY_IS_DRM          = 22;/*** This key retrieves the location information, if available.* The location should be specified according to ISO-6709 standard, under* a mp4/3gp box "@xyz". Location with longitude of -90 degrees and latitude* of 180 degrees will be retrieved as "-90.0000+180.0000", for instance.*/public static final int METADATA_KEY_LOCATION        = 23;/*** This key retrieves the video rotation angle in degrees, if available.* The video rotation angle may be 0, 90, 180, or 270 degrees.*/public static final int METADATA_KEY_VIDEO_ROTATION = 24;/*** This key retrieves the original capture framerate, if it's* available. The capture framerate will be a floating point* number.*/public static final int METADATA_KEY_CAPTURE_FRAMERATE = 25;/*** If this key exists the media contains still image content.*/public static final int METADATA_KEY_HAS_IMAGE       = 26;/*** If the media contains still images, this key retrieves the number* of still images.*/public static final int METADATA_KEY_IMAGE_COUNT     = 27;/*** If the media contains still images, this key retrieves the image* index of the primary image.*/public static final int METADATA_KEY_IMAGE_PRIMARY   = 28;/*** If the media contains still images, this key retrieves the width* of the primary image.*/public static final int METADATA_KEY_IMAGE_WIDTH     = 29;/*** If the media contains still images, this key retrieves the height* of the primary image.*/public static final int METADATA_KEY_IMAGE_HEIGHT    = 30;/*** If the media contains still images, this key retrieves the rotation* angle (in degrees clockwise) of the primary image. The image rotation* angle must be one of 0, 90, 180, or 270 degrees.*/public static final int METADATA_KEY_IMAGE_ROTATION  = 31;/*** If the media contains video and this key exists, it retrieves the* total number of frames in the video sequence.*/public static final int METADATA_KEY_VIDEO_FRAME_COUNT = 32;/*** @hide*/public static final int METADATA_KEY_EXIF_OFFSET = 33;/*** @hide*/public static final int METADATA_KEY_EXIF_LENGTH = 34;// Add more here...

如获取视频时长:

String METADATA_KEY_DURATION = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
Log.i(TAG, "onCreate: METADATA_KEY_DURATION="+METADATA_KEY_DURATION);

3: getFrameAtTime

该方法在任何时间位置找到一个有代表性的帧,并将其作为位图返回.

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {Bitmap frameAtTime =         mediaMetadataRetriever.getFrameAtTime();
}

如果需要获取指定时间,则可以调用

 public Bitmap getFrameAtTime(long timeUs) {return getFrameAtTime(timeUs, OPTION_CLOSEST_SYNC);}

4: getFrameAtIndex

用于从媒体文件中获取指定索引位置的帧图像.

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {Bitmap frameAtIndex = mediaMetadataRetriever.getFrameAtIndex(0);
}

5: getImageAtIndex

基于0的图像索引,返回位图信息.

Bitmap imageAtIndex = mediaMetadataRetriever.getImageAtIndex(0);

这里调用该方法时,会抛出IllegalStateException :

  java.lang.IllegalStateException: Does not contail still imagesat android.media.MediaMetadataRetriever.getImageAtIndexInternal(MediaMetadataRetriever.java:648)at android.media.MediaMetadataRetriever.getImageAtIndex(MediaMetadataRetriever.java:605)at com.test.media.MainActivity.lambda$onCreate$0$MainActivity(MainActivity.java:50)at com.test.media.-$$Lambda$MainActivity$fGcBDHveSBN77vUeMp6H1nheePE.onClick(Unknown Source:2)at android.view.View.performClick(View.java:7259)at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:967)at android.view.View.performClickInternal(View.java:7236)at android.view.View.access$3600(View.java:801)at android.view.View$PerformClick.run(View.java:27892)at android.os.Handler.handleCallback(Handler.java:894)at android.os.Handler.dispatchMessage(Handler.java:106)at android.os.Looper.loop(Looper.java:214)at android.app.ActivityThread.main(ActivityThread.java:7356)at java.lang.reflect.Method.invoke(Native Method)at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:491)at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:940)

具体的错误信息的原因如下:

private Bitmap getImageAtIndexInternal(int imageIndex, @Nullable BitmapParams params) {if (!"yes".equals(extractMetadata(MediaMetadataRetriever.METADATA_KEY_HAS_IMAGE))) {throw new IllegalStateException("Does not contail still images");}String imageCount = extractMetadata(MediaMetadataRetriever.METADATA_KEY_IMAGE_COUNT);if (imageIndex >= Integer.parseInt(imageCount)) {throw new IllegalArgumentException("Invalid image index: " + imageCount);}return _getImageAtIndex(imageIndex, params);
}

可以看到系统源码中校验了extractMetadata(MediaMetadataRetriever.METADATA_KEY_HAS_IMAGE)的值,如果值不是"yes",就会抛出"Does not contail still images".

与getImageAtIndex类似的方法还有:

getImageAtIndex(int, BitmapParams)
getPrimaryImage(BitmapParams)
getPrimaryImage()

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/791445.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Regression算法

文章目录 用线性回归找到最佳拟合直线标准回归函数局部加权线性回归函数 用线性回归找到最佳拟合直线 from google.colab import drive drive.mount("/content/drive")Mounted at /content/drivefrom numpy import *def loadDataSet(fileName):numFeat len(open(fi…

并发线程基础第八篇

目录 线程池 自定义线程池 步骤1:自定义拒绝策略接口 步骤2:自定义任务队列 步骤3:自定义线程池 步 骤 4:测 试 ThreadPoolExecutor 线程池状态 构造方法 工作方式 newFixedThreadPool newCachedThreadPool newSingleTh…

前端学习<四>JavaScript基础——02-JavaScript入门:hello world

开始写第一行 JavaScript:hello world JS 代码的书写位置在哪里呢?这个问题,也可以理解成:引入 JS 代码,有哪几种方式?有三种方式:(和 CSS 的引入方式类似) 行内式&…

C#开发中获取XML节点值,XML转对象案例

一、获取XML节点值 string strMsg"XML内容";XmlDocument xmlDoc new XmlDocument(); xmlDoc.LoadXml(strMsg);// 创建命名空间管理器 XmlNamespaceManager nsManager new XmlNamespaceManager(xmlDoc.NameTable); nsManager.AddNamespace("soapenv", &q…

我与C++的爱恋:内联函数,auto

​ ​ 🔥个人主页:guoguoqiang. 🔥专栏:我与C的爱恋 ​ 一、内联函数 1.内联函数的概念 内联函数目的是减少函数调用的开销,通过将每个调用点将函数展开来实现。这种方法仅适用于那些函数体小、调用频繁的函数。 …

redis事务(redis features)

redis支持事务,也就是可以在一次请求中执行多个命令。redis中的事务主要是通过MULTI和EXEC这两个命令来实现的。 MULTI命令用来开启一个事务,事务开启之后,所有的命令就都会被放入到一个队列中,最后通过一个EXEC命令来执行事务中…

基于java+SpringBoot+Vue的网上订餐系统设计与实现

基于javaSpringBootVue的网上订餐系统设计与实现 开发语言: Java 数据库: MySQL技术: Spring Boot JSP工具: IDEA/Eclipse、Navicat、Maven 系统展示 前台展示 菜品浏览与选择:用户可以浏览不同的菜品分类,并选择心仪的菜品。 订单创建与管理&…

任意文件下载漏洞

1.文件下载漏洞存在的位置 文件经过php处理可能存在文件下载漏洞,配合目录遍历漏洞使用 2.目录遍历漏洞检验方法 测试是否存在目录遍历漏洞:在网站网址中间添加随意写一个文件名../(返回上一级)进行测试,没有报错就…

备战蓝桥杯--数论与搜索刷题2

话不多说,直接看题: 1.辗转相减法 我们不妨假设原等比数列a,a*(q/p),a*(q/p)^2.... 那么x1,,,,xn就是其中的n项,xi/x1(q/p)^b,假设最大比例为(q/p)^k,,那么一定有(q/p)^(k*s)(q/p)^b,即k是b的…

【Servlet】Servlet入门

文章目录 一、介绍二、入门案例导入servlet-api的解决办法 一、介绍 概念:server applet,即:运行在服务器端的小程序 Servlet就是一个接口,定义了Java类被浏览器访问到(tomcat识别)的规则。 将来我们定义…

【项目新功能开发篇】开发编码

作者介绍:本人笔名姑苏老陈,从事JAVA开发工作十多年了,带过大学刚毕业的实习生,也带过技术团队。最近有个朋友的表弟,马上要大学毕业了,想从事JAVA开发工作,但不知道从何处入手。于是&#xff0…

mysql 磁盘空间100%

MySQL大事务可能会导致过多的占用临时文件,导致磁盘空间撑满的问题 本例说明下binlog cache产生的临时文件 案例复现 调小binlog_cache_size,让DML使用临时文件 使用存储过程模拟大事务 创建表 create table t1( id int AUTO_INCREMENT, name varchar…

Rust---复合数据类型之字符串与切片(2)

目录 字符串操作删除 (Delete)连接 (Concatenate) 字符串转义 前情回顾: Rust—复合数据类型之字符串(1) 字符串操作 删除 (Delete) 删除方法仅适用于 String 类型,分别是: pop(),remove(),truncate()&a…

【Redis系列】Redis安装与使用

💝💝💝欢迎来到我的博客,很高兴能够在这里和您见面!希望您在这里可以感受到一份轻松愉快的氛围,不仅可以获得有趣的内容和知识,也可以畅所欲言、分享您的想法和见解。 推荐:kwan 的首页,持续学…

使用subprocess包来在python代码实时查看GPU利用率

最近又被GPU利用率问题导致训练不高效的问题搞到了(恼),所以在py使用代码看看是哪出了问题。 import subprocessdef get_gpu_utilization():# 运行nvidia-smi命令smi_output subprocess.check_output([nvidia-smi, --query-gpuutilization.…

保研线性代数复习3

一.基底(Basis) 1.什么是生成集(Generating Set)?什么是张成空间(Span)? 存在向量空间V(V,,*),和向量集(xi是所说的列向量&#xff…

大模型prompt技巧——思维链(Chain-of-Thought)

1、Zero-shot、One-shot、Few-shot 与fintune prompt的时候给出例子答案,然后再让模型回答。 2、zero-shot-CoT “Let’s think step by step”有奇迹效果 3、多数投票提高CoT性能——自洽性(Self-consistency) 多个思维链,然后取…

WordPress 6.5 “里贾纳”已经发布

WordPress 6.5 “里贾纳”已经发布,其灵感来自著名爵士小提琴家Regina Carter的多才多艺。雷吉娜是一位屡获殊荣的艺术家和著名的爵士乐教育家,以超越流派而闻名,她在古典音乐方面的技术基础和对爵士乐的深刻理解为她赢得了大胆超越小提琴所能…

数据库面试题之Mysql

(1)Mysql主从架构原理 主库把数据变更写入binlog从库的IO线程对主库发起dump请求主库IO线程推送binlog至从库从库IO线程写入本地relay log从库sql线程读取relay log,保持和主库数据一致(2)B+树和B树的区别? 结构方面: B树每个节点可以有多于一个的关键字,而非叶子节点可…

修改element-ui table组件展开/收起图标、支持点击行展开/收起、隐藏不可展开行得图标

Element中table默认支持的,展开和收起功能,如下: 针对表格的展开收起,本文改造的主要有3点: 1、修改展开/收起的图标; 2、对于不支持展开/收起的行,隐藏图标; 3、点击行&#xff0…