继续Android课程的学习。主要学习了在Android平台下面播放MP3音乐的技巧。通过今天的学习,为后面开发应用过程中为应用程序添加背景音乐,以及开发音乐播放器打下基础。
以下是我们从MediaPlayer类中得到的MediaPlayer对象的一个状态图:
首先,我们打开Android开发文档Dev Guide标签,找到Audio and Video开发页。在该页中为我们详细介绍了使用类MediaPlayer播放音乐的方法。总结内容如下:
播放文件类型:
- raw resource:主要存储在应用程序的资源文件中,例如:背景音乐。
- file system resource:处于Android文件系统中的音乐文件。
- networking stream:网络流音乐文件
开发方法:
关于raw resource开发
- 将音乐文件存储在应用程序中的 /res/raw目录中。Eclipse插件将会对文件进行编译,可以通过R类中的资源标识符引用该音乐文件。
- 通过MediaPlayer类中的静态方法create(context,resid)创建播放器(在调用creat()方法时候,系统会自动调用prepare()方法,是的播放器对象进入Prepared状态)。当要播放文件的时候调用start()方法,则播放器对象进入如上图的Started状态。
- 当需要停止播放文件的时候调用stop()方法(当调用stop()后,播放器对象将转入Stopped状态),如果用户在播放器处于Stopped状态后,下次还想播放该文件,则首先需要通过调用prepare()方法将程序转入Prepared状态,随后调用start()可以继续播放文件。
- 当需要暂停播放文件的时候调用pause()方法,需要继续播放调用start()方法即可。
关于 file system resource 和 networking stream文件开发
- 使用new 方法创建播放器,播放器对象处于Idle状态;
- 使用setDataSource()设置文件本地路径或文件的网络路径,播放器对象处于Initialized状态;
- 调用 prepare()方法,进入Prepared状态;
- 调用start()方法,进入Started状态;
- 有关stop()以及pause()方法的使用和raw resource文件开发类似;
下面是一个测试例子,对上面讲述的内容进行简单的应用:
main.xml
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical" android:layout_width="fill_parent"
- android:layout_height="fill_parent">
- <RadioGroup android:orientation="vertical" android:layout_width="wrap_content" android:layout_height="wrap_content">
- <RadioButton android:id="@+id/rawRadioButton"
- android:text="raw" android:layout_width="wrap_content"
- android:layout_height="wrap_content"></RadioButton>
- <RadioButton android:id="@+id/fileRadioButton"
- android:text="file" android:layout_width="wrap_content"
- android:layout_height="wrap_content"></RadioButton>
- </RadioGroup>
- <Button android:id="@+id/startButton" android:layout_width="wrap_content"
- android:layout_height="wrap_content" android:text="start" />
- <Button android:id="@+id/pauseButton" android:layout_width="wrap_content"
- android:layout_height="wrap_content" android:text="pause" />
- <Button android:id="@+id/stopButton" android:layout_width="wrap_content"
- android:layout_height="wrap_content" android:text="stop" />
- </LinearLayout>