MediaStore类向存储在设备上(无论是内部存储器还是外部存储器)的媒体提供了一个接口,MediaStore还提供了API来操作媒体。这些API中包含在设备上搜索特定类型的媒体的机制,用于将音频和视频录制到存储器的Intent,及建立播放列表的方式。 MediaStore便于简化操作。下面是使用Intent来录制音频和拍照的简单示例。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
public class MediaStoreTest extends Activity {
private static final String TAG = "MediaStoreTest";
private static final int RECORD_SOUND = 0;
private static final int IMAGE_CAPTURE = 1;
private Button btnRecord;
private Button btnPhoto;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnRecord = (Button)findViewById(R.id.btnRecord);
btnRecord.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
startRecording();
}
});
btnPhoto = (Button)findViewById(R.id.btnPhoto);
btnPhoto.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
takePhoto();
}
});
}
public void startRecording() {
Intent intent = new Intent("android.provider.MediaStore.RECORD_SOUND");
startActivityForResult(intent, RECORD_SOUND);
}
public void takePhoto() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
String strFilePath = Environment.getExternalStorageDirectory() + "/take_photo/" + getDate() + ".jpeg";
Log.d(TAG, "strFilePath:" + strFilePath);
Uri uri = Uri.fromFile(new File(strFilePath));
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri); // 设置照片的保存路径
startActivityForResult(intent, IMAGE_CAPTURE);
}
/**
* 获取系统时间
* @return
*/
public static String getDate(){
Calendar ca = Calendar.getInstance();
int year = ca.get(Calendar.YEAR);// 获取年份
int month = ca.get(Calendar.MONTH);// 获取月份
int day = ca.get(Calendar.DATE);// 获取日
int hour = ca.get(Calendar.HOUR);// 获取小时
int minute = ca.get(Calendar.MINUTE);// 获取分
int second = ca.get(Calendar.SECOND);// 获取秒
int millisecond = ca.get(Calendar.MILLISECOND); // 获取毫秒
String date = "" + year + (month + 1 ) + day + hour + minute + second + millisecond;
return date;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
switch(requestCode) {
case RECORD_SOUND:
if (resultCode == RESULT_OK) {
Uri recordAudioPath = data.getData();
Log.d(TAG, "recordAudioPath:" + recordAudioPath);
}
break;
case IMAGE_CAPTURE:
//if (resultCode == RESULT_OK) {
//Bitmap bmp = (Bitmap)data.getExtras().get("data");
//Log.d(TAG, "bmp width:" + bmp.getWidth() + ", height:" + bmp.getHeight());
//}
break;
default:
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
}