android怎样取mp4时长
时间: 2023-07-28 16:34:35 浏览: 65
在 Android 中,你可以使用 `MediaMetadataRetriever` 类来获取 MP4 文件的时长。以下是示例代码:
```java
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
retriever.setDataSource("path/to/your/mp4/file"); // 设置文件路径
// 获取视频时长
String durationStr = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
long duration = Long.parseLong(durationStr);
// 将时长转换为秒
duration = duration / 1000;
Log.d("TAG", "视频时长为:" + duration + " 秒");
// 释放资源
retriever.release();
```
在上述代码中,我们使用 `setDataSource()` 方法设置了要获取信息的 MP4 文件的路径,然后使用 `extractMetadata()` 方法获取文件的元数据信息,其中 `MediaMetadataRetriever.METADATA_KEY_DURATION` 表示获取视频时长。最后,我们将获取到的时长字符串转换为长整型并除以 1000 转换为秒。最后别忘了调用 `release()` 方法释放资源。
需要注意的是,如果你想获取网络上的 MP4 文件的时长,需要使用 `setDataSource()` 方法的不同重载版本,将 URL 作为参数传入。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)