11.安卓基础之多媒体

Android 多媒体基础知识

概述

计算机发展到今天,不仅表示数值和符号,已具有了对文本,图形,图像动画及音频视频等多种信息的综合处理能力,我们称之为多媒体技术.

图像与图形

在计算机中,
图像是采用位图形式来表示的;
图形是采用矢量图方式来表示的;

位图图像

称为光栅图点阵图像,是由许多像小方块一样的”像素”(pixels)组成的图形.
位图图像

  • 图像 : 是由像素点阵组成的画面.
  • 位图 : 由许多点组成的点阵图.构成位图的点称为像素.
  • 色彩深度 : 位图所能达到的最大颜色数,称为色彩深度.(对于黑白两种颜色的图像来说一个像素点可用一个二进制位来表示,如0表示黑色,1表示白色.)

图片的操作

1
2
3
4
5
6
7
8
9
10
11
12
// 1. 准备画纸:(大小和材质需要参考原图)
Bitmap copyBitmap = Bitmap.createBitmap(srcBitmap.getWidth(),
srcBitmap.getHeight(), srcBitmap.getConfig());
// 2. 准备画板,将画纸放到画板上
Canvas canvas = new Canvas(copyBitmap);
// 3. 准备画笔
Paint paint = new Paint();
// 4. 按照一定的规则
Matrix matrix = new Matrix();// 1:1照着画
// 5. 将原图像按照规则画到画板上
canvas.drawBitmap(srcBitmap, matrix, paint);
  • 图片的缩放

    1
    matrix.setScale(0.6f, 0.8f);
  • 图片的平移

    1
    matrix.setTranslate(50, 50);

位图图像的缺陷

  • 位图放大和缩小都会引起像素的增加或减少,这样会使得原由的图像的线条和形状变得参差不齐,与原图像相比出现失真;出现”锯齿形”.

位图

位图常见的文件格式

  • .bmp
  • .jpg
  • .gif
  • .png

矢量图像

矢量图形是通过计算机将一串线条和图形转换为一系列指令,在计算机中只存储这些指令,而不是像素.矢量图像看起来没有位图图像真实,但矢量图形的存储空间比位图图像要小得多,而且矢量图像通过拉伸,移动,放大等操作,图像不会产生实真.

矢量图像

颜色矩阵

1 0 0 0 0
0 1 0 0 0
0 0 1 0 0
0 0 0 1 0

颜色矩阵的代码表述

1
2
3
4
5
6
7
8
9
10
11
12
13
New Red Value = 1*128 + 0*128 + 0*128 + 0*0 + 0
New Green Value = 0*128 + 1*128 + 0*128 + 0*0 + 0
New Blue Value = 0*128 + 0*128 + 1*128 + 0*0 + 0
New Alpha Value = 0*128 + 0*128 + 0*128 + 1*0 + 0
ColorMatrix cm = new ColorMatrix();
cm.set(new float[] {
2, 0, 0, 0, 0,
0, 1, 0, 0, 0,
0, 0, 1, 0, 0,
0, 0, 0, 1, 0
});
paint.setColorFilter(new ColorMatrixColorFilter(cm));

传感器

传感器(英文名称 : sensor)是一种检测装置,能感受到被测量的信息,并能将感受到的信息,按一定规律变换成为电信号或其他所需形式的信息输出,以满足信息的传输,处理,存储,显示,记录和控制等要求.

传感器的特点包括 : 微型化,数字化,智能化,多功能化,系统化,网络化.它是实现自动检测和自动控制的首要环节.传感器的存在和发展,让物体有了触觉,味觉和嗅觉等感官,让物体慢慢变得活了起来.通常根据其基本感知功能分为热敏元件,光敏元件,气敏元件,力敏元件,磁敏元件,湿敏元件,声敏元件,放射线敏感元件,色敏元件和味敏元件等十大类.

传感器

传感器类型 描述
SENSOR_TYPE_ACCELEROMETER 加速度
SENSOR_TYPE_MAGNETIC_FIELD 磁力
SENSOR_TYPE_ORIENTATION 方向
SENSOR_TYPE_GYROSCOPE 陀螺仪
SENSOR_TYPE_LIGHT 光线感应
SENSOR_TYPE_PRESSURE 压力
SENSOR_TYPE_TEMPERATURE 温度
SENSOR_TYPE_PROXIMITY 接近
SENSOR_TYPE_GRAVITY 重力
SENSOR_TYPE_LINEAR_ACCELERATION 线性加速度

练习案例

  • 加载大图片到内存

获取到读写内存权限

1
2
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>

代码实现部分

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
private ImageView iv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv =(ImageView) findViewById(R.id.iv);
}
public void loadBitmap(View v){
String path = "mnt/sdcard/1.jpg";
//通过手机的屏幕的宽高和图片的宽高来计算采样率
//屏幕宽高
DisplayMetrics metrics = getResources().getDisplayMetrics();
int screenWidth = metrics.widthPixels;//获取屏幕宽度
int screentHeight = metrics.heightPixels;//获取屏幕高度
//图片的宽高
try{
ExifInterface exif = new ExifInterface(path);
int picWidth = exif.getAttributeInt(ExifInterface.TAG_IMAGE_WIDTH,0);
int picHeight = exif.getAttributeInt(ExifInterface.TAG_IMAGE_LENGTH,0);
//用图片的宽度/屏幕的宽度
int widthSample = (int)(picWidth*1f/screenWidth+0.5f);//四舍五入
int heightSample = (int)(picHeight*1f/screentHeight+0.5f);//四舍五入
int sample = (int) (Math.sqrt(widthSample * widthSample
+ heightSample * heightSample) + 0.5f);
//加载图片
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inSampleSize = sample;//采样率
Bitmap bitmap = BitmapFactory.decodeFile(path,opts);
iv.setImageBitmap(bitmap);
}catch (Exception e){
e.printStackTrace();
}
}
}
  • 图片的缩放
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public void opts(View v){
String path = "mnt/sdcard/1.jpg";
//显示图片
Bitmap srcBitmap = BitmapFactory.decodeFile(path);
ivSrc.setImageBitmap(srcBitmap);
//准备画纸(大小和材质参照原材料)
Bitmap copyBitmap = Bitmap.createBitmap(srcBitmap.getWidth(),srcBitmap.getHeight(),srcBitmap.getConfig());
//准备画板,将画纸放到画板上
Canvas canvas = new Canvas(copyBitmap);
//准备画笔
Paint paint = new Paint();
//按照一定规则
Matrix matrix = new Matrix();//1:1画
//按照比例缩放图片
matrix.setScale(24.6f,22.8f);
//将原图像按照规则画到画板上
canvas.drawBitmap(srcBitmap,matrix,paint);
//画板有数据了
ivDest.setImageBitmap(copyBitmap);
}
  • 图片的位移
1
2
// 位移操作:dx:x方向的增量 dy:y方向的增量
matrix.setTranslate(50, 50);
  • 图片的旋转
1
2
matrix.setRotate(45, srcBitmap.getWidth() / 2f,
srcBitmap.getHeight() / 2f);
  • 对图片颜色的处理
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
public class MainActivity extends Activity implements OnSeekBarChangeListener {
private ImageView iv;
private SeekBar skbRed;
private SeekBar skbGreen;
private SeekBar skbBlue;
private float redPercent = 1;
private float greenPercent = 1;
private float bluePercent = 1;
private Bitmap srcBitmap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv = (ImageView) findViewById(R.id.iv);
skbRed = (SeekBar) findViewById(R.id.skb_red);
skbGreen = (SeekBar) findViewById(R.id.skb_green);
skbBlue = (SeekBar) findViewById(R.id.skb_blue);
skbRed.setOnSeekBarChangeListener(this);
skbGreen.setOnSeekBarChangeListener(this);
skbBlue.setOnSeekBarChangeListener(this);
// 加载图片显示
String path = "mnt/sdcard/img_small_1.jpg";
srcBitmap = BitmapFactory.decodeFile(path);
iv.setImageBitmap(srcBitmap);
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// seekbar进度改变时的回调
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// 开始拖动seekbar的回调
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// 停止拖动seekbar的回调
// 0-100;//0-2
int progress = seekBar.getProgress();
float percent = progress / 50f;// (0-2f)
if (seekBar == skbRed) {
this.redPercent = percent;
} else if (seekBar == skbGreen) {
this.greenPercent = percent;
} else if (seekBar == skbBlue) {
this.bluePercent = percent;
}
// 去改变图片的颜色
// 1.去获得图片的拷贝
Bitmap copyBitmap = Bitmap.createBitmap(srcBitmap.getWidth(),
srcBitmap.getHeight(), srcBitmap.getConfig());
Canvas canvas = new Canvas(copyBitmap);
Matrix matrix = new Matrix();
// 2.去处理图片的中的颜色数据
Paint paint = new Paint();
// 设置画笔的颜色过滤
// vector:0-2 0:没有 2:最多
float[] cm = new float[] { 1 * redPercent, 0, 0, 0, 0, // red vector
0, 1 * greenPercent, 0, 0, 0, // green vector
0, 0, 1 * bluePercent, 0, 0, // blue vector
0, 0, 0, 1, 0 // alpha vector
};
paint.setColorFilter(new ColorMatrixColorFilter(new ColorMatrix(cm)));
canvas.drawBitmap(srcBitmap, matrix, paint);
// 3.将处理的结果展示
iv.setImageBitmap(copyBitmap);
}
}
  • canvas相关api
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
public class MainActivity extends Activity {
private ImageView iv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv = (ImageView) findViewById(R.id.iv);
}
public void line(View view) {
// 1.画线
// 准备画纸
Bitmap bitmap = Bitmap.createBitmap(320, 320, Config.ARGB_8888);
// 准备画布
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint();
canvas.drawLine(10, 10, 200, 200, paint);
iv.setImageBitmap(bitmap);
}
public void rect(View view) {
// 1.画矩形
// 准备画纸
Bitmap bitmap = Bitmap.createBitmap(320, 320, Config.ARGB_8888);
// 准备画布
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint();
// 设置画笔的颜色
paint.setColor(Color.RED);
// 设置画笔的样式
paint.setStyle(Style.STROKE);
paint.setStrokeWidth(10);// 设置粗细
canvas.drawRect(30, 30, 200, 200, paint);
iv.setImageBitmap(bitmap);
}
public void circle(View view) {
// 1.画圆形
// 准备画纸
Bitmap bitmap = Bitmap.createBitmap(320, 320, Config.ARGB_8888);
// 准备画布
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint();
// 设置画笔的颜色
paint.setColor(Color.RED);
paint.setAntiAlias(true);// 设置抗锯齿
float cx = 160;// 圆心的坐标X
float cy = 160;// 圆心的坐标Y
float radius = 100;// 半径
canvas.drawCircle(cx, cy, radius, paint);
iv.setImageBitmap(bitmap);
}
public void arc(View view) {
// 1.扇形
// 准备画纸
Bitmap bitmap = Bitmap.createBitmap(320, 320, Config.ARGB_8888);
// 准备画布
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint();
paint.setColor(Color.RED);
paint.setAntiAlias(true);// 设置抗锯齿
// 1:矩形
RectF oval = new RectF(20, 20, 200, 200);
float startAngle = 0;// 起始角度
float sweepAngle = 120;// 扫过的角度
boolean useCenter = false;// 是否画中心部分
canvas.drawArc(oval, startAngle, sweepAngle, useCenter, paint);
iv.setImageBitmap(bitmap);
}
public void trangle(View view) {
// 1.多边形
// 准备画纸
Bitmap bitmap = Bitmap.createBitmap(320, 320, Config.ARGB_8888);
// 准备画布
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint();
paint.setColor(Color.RED);
paint.setAntiAlias(true);// 设置抗锯齿
float x1 = 160;
float y1 = 20;
float x2 = 140;
float y2 = 200;
float x3 = 180;
float y3 = 200;
Path path = new Path();
path.moveTo(x1, y1);// 将画笔移动到点1
path.lineTo(x2, y2);// 连线点2
path.arcTo(new RectF(140, 180, 180, 220), 0, 180);
path.lineTo(x3, y3);// 连线点3
path.lineTo(x1, y1);// 连线点1
path.close();
canvas.drawPath(path, paint);
iv.setImageBitmap(bitmap);
}
}
  • 画画板

Menu的写法 :

1
2
3
4
5
6
7
8
9
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/action_save"
android:orderInCategory="100"
android:showAsAction="never"
android:title="保存图片"/>
</menu>

布局写法 :

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
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<View
android:id="@+id/color_red"
android:layout_width="35dp"
android:layout_height="35dp"
android:background="#ff0000" />
<View
android:id="@+id/color_green"
android:layout_width="35dp"
android:layout_height="35dp"
android:background="#00ff00" />
<View
android:id="@+id/color_blue"
android:layout_width="35dp"
android:layout_height="35dp"
android:background="#0000ff" />
<View
android:id="@+id/color_yellow"
android:layout_width="35dp"
android:layout_height="35dp"
android:background="#ffff00" />
<View
android:id="@+id/color_pink"
android:layout_width="35dp"
android:layout_height="35dp"
android:background="#ff99ff" />
</LinearLayout>
<!-- 画笔的粗细 -->
<SeekBar
android:id="@+id/skb_stroke"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<ImageView
android:id="@+id/iv"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>

Java代码的实现 :

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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
public class MainActivity extends Activity implements OnClickListener,
OnSeekBarChangeListener, OnTouchListener {
private static final String TAG = "MainActivity";
private View redView;
private View greenView;
private View blueView;
private View yellowView;
private View pinkView;
private SeekBar skbStroke;
private ImageView iv;
private Bitmap bitmap;
private Canvas canvas;
private Paint paint;
private float startX;
private float startY;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
redView = findViewById(R.id.color_red);
greenView = findViewById(R.id.color_green);
blueView = findViewById(R.id.color_blue);
yellowView = findViewById(R.id.color_yellow);
pinkView = findViewById(R.id.color_pink);
skbStroke = (SeekBar) findViewById(R.id.skb_stroke);
iv = (ImageView) findViewById(R.id.iv);
redView.setOnClickListener(this);
greenView.setOnClickListener(this);
blueView.setOnClickListener(this);
yellowView.setOnClickListener(this);
pinkView.setOnClickListener(this);
skbStroke.setOnSeekBarChangeListener(this);
iv.setOnTouchListener(this);
// 准备画纸画布画笔
bitmap = Bitmap.createBitmap(320, 320, Config.ARGB_8888);
canvas = new Canvas(bitmap);
paint = new Paint();
canvas.drawColor(Color.WHITE);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
// 更改画笔的颜色
case R.id.color_red:
paint.setColor(Color.RED);
break;
case R.id.color_green:
paint.setColor(Color.GREEN);
break;
case R.id.color_blue:
paint.setColor(Color.BLUE);
break;
case R.id.color_yellow:
paint.setColor(Color.YELLOW);
break;
case R.id.color_pink:
paint.setColor(0xffff99ff);
break;
default:
break;
}
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// 改变画笔的粗细
int progress = seekBar.getProgress();// 0-100(1sp--->10sp)
// paint.setStrokeWidth(progress);
paint.setStrokeWidth(10 * progress / 100f);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
// 触摸Imageview的回调
// 触摸的时候需要绘制图像,并且显示
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:// 1次
// 1. 手指按下
startX = event.getX();// 触摸的x坐标
startY = event.getY();// 触摸的y坐标
break;
case MotionEvent.ACTION_MOVE:// 0-多次
// 2. 手指移动
float stopX = event.getX();
float stopY = event.getY();
// 绘制图像,并且显示到imgeview上
canvas.drawLine(startX, startY, stopX, stopY, paint);
// 画纸上有数据了
iv.setImageBitmap(bitmap);
// 更新起始点
startX = stopX;
startY = stopY;
break;
case MotionEvent.ACTION_UP:// 1次
// 3. 手指抬起
break;
default:
break;
}
// 消费触摸事件
return true;
}
// 对应的菜单按钮
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
// 菜单按钮的点击事件
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int itemId = item.getItemId();
switch (itemId) {
case R.id.action_save:
Log.d(TAG, "点击了保存按钮!");
// 将bitmap存储到本地
File file = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
// 将bitmap压缩到流中
bitmap.compress(CompressFormat.JPEG, 100, fos);
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
fos = null;
}
}
// 模拟 sdcard的挂载
Intent intent = new Intent(Intent.ACTION_MEDIA_MOUNTED);
intent.setData(Uri.fromFile(Environment
.getExternalStorageDirectory()));
sendBroadcast(intent);
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
}

  • 播放器的同步和异步

播放网络歌曲权限 :

1
<uses-permission android:name="android.permission.INTERNET"/>

播放器的代码实现 :

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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
public class MainActivity extends Activity implements OnSeekBarChangeListener {
private EditText etPath;
private SeekBar skbProgress;
private MediaPlayer player;
private boolean tracking = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etPath = (EditText) findViewById(R.id.et_path);
skbProgress = (SeekBar) findViewById(R.id.skb_progress);
skbProgress.setOnSeekBarChangeListener(this);
}
public void play(View view) {
String path = etPath.getText().toString().trim();
if (TextUtils.isEmpty(path)) {
return;
}
// 播放音乐
if (player == null) {
player = new MediaPlayer();
}
// 重置播放器
player.reset();
try {
player.setOnErrorListener(new OnErrorListener() {
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
System.out.println("what : " + what);
return false;
}
});
// 设置播放的资源
player.setDataSource(path);
player.prepare();// 准备播放
player.start();// 开始播放
performProgress();
} catch (Exception e) {
e.printStackTrace();
}
}
private void performProgress() {
skbProgress.setMax(player.getDuration());// 音乐文件的时长
new Thread(new Runnable() {
@Override
public void run() {
while (player != null && player.isPlaying()) {
if (!tracking) {
// 获得当前的进度
int currentPosition = player.getCurrentPosition();
skbProgress.setProgress(currentPosition);//子线程中更新UI
}
}
}
}).start();
}
public void pause(View view) {
// 暂停
if (player != null && player.isPlaying()) {
player.pause();
((Button) view).setText("继续");
} else if (player != null) {
player.start();
performProgress();
((Button) view).setText("暂停");
}
}
public void stop(View view) {
if (player != null) {
player.stop();
player.release();// 释放资源
player = null;
}
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// 开始拖动
tracking = true;
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// 结束拖动
tracking = false;
// 播放对应的位置
if (player != null) {
player.seekTo(seekBar.getProgress());
}
}
}
  • 声音池
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
public class MainActivity extends Activity {
private SoundPool pool;
private int soundID;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int maxStreams = 10;// 声音池中同时可以播放声音的数量
int streamType = AudioManager.STREAM_MUSIC;
int srcQuality = 0;
pool = new SoundPool(maxStreams, streamType, srcQuality);
// 加载一个声音文件
soundID = pool.load(this, R.raw.shoot, 1);
}
public void shoot(View view) {
float leftVolume = 1f;
float rightVolume = 1f;
int priority = 0;
int loop = 0;
float rate = 1;// 播放的速率
pool.play(soundID, leftVolume, rightVolume, priority, loop, rate);
}
}
  • 视频播放器

xml界面的简写 :

1
2
3
4
<VideoView
android:id="@+id/vv"
android:layout_width="match_parent"
android:layout_height="match_parent" />

Java代码的实现 :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class MainActivity extends Activity {
private VideoView vv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
vv = (VideoView) findViewById(R.id.vv);
MediaController mc = new MediaController(this);
mc.setAnchorView(vv);
vv.setMediaController(mc);
vv.setVideoPath("mnt/sdcard/areyouok.3gp");
vv.start();
}
}

  • 拍照
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
public class MainActivity extends Activity {
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void takephoto(View view) {
// create Intent to take a picture and return control to the calling
// application
// 意图
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);// 去打开系统的照相机
// 准备一个接收系统拍好照片后的文件路径
File file = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file)); // set the
// image
// file
// name
// start the image capture Intent
// 请求code
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
// 为你的某个请求返回的结果
// 给你数据的Activity设置的结果标记
// resultCode
switch (resultCode) {
case Activity.RESULT_OK:
// 获取数据成功
System.out.println("ok");
break;
case Activity.RESULT_CANCELED:
// 用户取消操作
System.out.println("cancel");
break;
default:
break;
}
}
}
}
  • 传感器指南针
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
public class MainActivity extends Activity {
private SensorManager manager;
private Sensor sensor;
private SensorEventListener listener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
// 1. 获取 传感器的数据
float[] values = event.values;
// value
// values[0]: Azimuth, angle between the magnetic north direction
// and the y-axis, around the z-axis (0 to 359). 0=North, 90=East,
// 180=South, 270=West
float angle = values[0];
if (angle == 0) {
System.out.println("北");
} else if (angle == 90) {
System.out.println("东");
} else if (angle == 180) {
System.out.println("南");
} else if (angle == 270) {
System.out.println("西");
} else if (angle > 0 && angle < 90) {
System.out.println("东北");
} else if (angle > 90 && angle < 180) {
System.out.println("东南");
} else if (angle > 180 && angle < 270) {
System.out.println("西南");
} else if (angle > 270 && angle < 360) {
System.out.println("西北");
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// 1. 传感器的精确度发送改变时
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 传感器的管理者
manager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
// List<Sensor> list = manager.getSensorList(Sensor.TYPE_ALL);
// for (Sensor sensor : list) {
// System.out.println(sensor.getName());
// }
// 获得光的传感器
sensor = manager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
}
@Override
protected void onResume() {
super.onResume();
// 1:监听传感器
// 2:哪个传感器
// 3:采样频率
manager.registerListener(listener, sensor,
SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
protected void onPause() {
super.onPause();
manager.unregisterListener(listener);
}
}