Android读取音视频有两种方法:
遍历sd卡根据文件后缀名读取(太耗时优先级低)
利用内容提供器来提取音视频(优先级高)
1.第一步,建立mediaitem的bean基类
package com.example.ztest.bean;
import java.io.Serializable;
public class MediaItem implements Serializable {
private String name;
private long size;
private long duration;
private String data;
private String artist;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getSize() {
return size;
}
public void setSize(long size) {
this.size = size;
}
public long getDuration() {
return duration;
}
public void setDuration(long duration) {
this.duration = duration;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public String getArtist() {
return artist;
}
public void setArtist(String artist) {
this.artist = artist;
}
@Override
public String toString() {
return "MediaItem [name=" + name + ", size=" + size + ", duration="
+ duration + ", data=" + data + ", artist=" + artist + "]";
}
}
2.第二步就是写个方法去读取了(我只贴个方法了哦)
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (items != null && items.size() > 0) {
//进行相关操作
} else {
Toast.makeText(TestAty.this, "没有找到视频", Toast.LENGTH_SHORT);
}
}
};
private void GetDataFormLocal() {
items = new ArrayList
new Thread() {
@Override
public void run() {
super.run();
ContentResolver resolver = TestAty.this.getContentResolver();// 获取内容提供者
Uri uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;// 获取外部存储的uri
String[] objs = { MediaStore.Video.Media.DISPLAY_NAME,// 视频文件的名字
MediaStore.Video.Media.SIZE,// 视频文件的大小
MediaStore.Video.Media.DURATION,// 视频文件的总时长
MediaStore.Video.Media.DATA,// 视频文件的绝对地址
MediaStore.Video.Media.ARTIST,// 音频文件的作者
};
Cursor cursor = resolver.query(uri, objs, null, null, null);
if (cursor != null) {
while (cursor.moveToNext()) {
MediaItem item = new MediaItem();
String name = cursor.getString(0);
long size = cursor.getLong(1);
long duration = cursor.getLong(2);
String data = cursor.getString(3);
String artist = cursor.getString(4);
item.setName(name);
item.setSize(size);
item.setDuration(duration);
item.setData(data);
item.setArtist(artist);
items.add(item);
}
cursor.close();
}
handler.sendEmptyMessage(0);
}
}.start();
}
相信大家应该都看得懂吧(有相关注释),下面cursor读取就是根据我们查询的数组顺序相对应的,然后获取完毕我么就利用一个handler发送一个消息,再对其进行处理。这样就完成了视频的读取,音频也一样的,只要将相关的MediaStore.Video.Media改成MediaStore.Audio.Media就行了这样获取的就是音频文件的相关属性。
热点新闻