本文介绍MediaPlayer的使用。MediaPlayer可以播放音频和视频,另外也可以通过VideoView来播放视频,虽然VideoView比MediaPlayer简单易用,但定制性不如用MediaPlayer,要视情况选择了。MediaPlayer播放音频比较简单,但是要播放视频就需要SurfaceView。SurfaceView比普通的自定义View更有绘图上的优势,它支持完全的OpenGL ES库。
先贴出本文程序运行结果的截图,下面是上一首、下一首、播放、停止、自动下一首、可用SeekBar来调进度:
布局文件:
1 <?xml version="1.0" encoding="utf-8"?>
2 <LinearLayout
3 xmlns:android="http://schemas.android.com/apk/res/android"
4 xmlns:app="http://schemas.android.com/apk/res-auto"
5 xmlns:tools="http://schemas.android.com/tools"
6 android:layout_width="match_parent"
7 android:layout_height="match_parent"
8 android:orientation="vertical"
9 tools:context="net.bwie.mediaplayer.MainActivity">
10
11 <RelativeLayout
12 android:layout_width="match_parent"
13 android:layout_height="wrap_content">
14
15 <TextView
16 android:id="@+id/current_time_tv"
17 android:layout_width="wrap_content"
18 android:layout_height="wrap_content"
19 android:text="当前时间"/>
20
21 <TextView
22 android:id="@+id/total_time_tv"
23 android:layout_width="wrap_content"
24 android:layout_height="wrap_content"
25 android:layout_alignParentRight="true"
26 android:text="全部时间"/>
27
28 <SeekBar
29 android:id="@+id/seek_bar"
30 style="?android:progressBarStyleHorizontal"
31 android:layout_width="match_parent"
32 android:layout_height="50dp"
33 android:layout_toLeftOf="@id/total_time_tv"
34 android:layout_toRightOf="@id/current_time_tv"/>
35
36 </RelativeLayout>
37
38 <LinearLayout
39 android:layout_width="match_parent"
40 android:layout_height="wrap_content">
41
42 <Button
43 android:id="@+id/previous_btn"
44 android:layout_width="0dp"
45 android:layout_height="wrap_content"
46 android:layout_weight="1"
47 android:text="上一曲"/>
48
49 <Button
50 android:id="@+id/play_btn"
51 android:layout_width="0dp"
52 android:layout_height="wrap_content"
53 android:layout_weight="1"
54 android:text="播放/暂停"/>
55
56 <Button
57 android:id="@+id/next_btn"
58 android:layout_width="0dp"
59 android:layout_height="wrap_content"
60 android:layout_weight="1"
61 android:text="下一曲"/>
62
63 </LinearLayout>
64
65
66 <ListView
67 android:id="@+id/list_view"
68 android:layout_width="match_parent"
69 android:layout_height="match_parent"
70 android:divider="#f00"
71 android:dividerHeight="2dp"/>
72
73 </LinearLayout>
Bean类:
1 package net.bwie.mediaplayer.bean;
2
3 public class MediaInfo {
4
5 private long _id;
6 private String uri;// 路径
7 private String title;
8 private String artist;// 艺术家
9
10 public MediaInfo(