这里有新鲜出炉的精品教程,程序狗速度看过来!
Android 是一种基于 Linux 的自由及开放源代码的操作系统,主要使用于移动设备,如智能手机和平板电脑,由 Google 公司和开放手机联盟领导及开发。尚未有统一中文名称,中国大陆地区较多人使用 "安卓" 或 "安致"。
这篇文章主要介绍了 Android 开发之 MediaPlayer 基本使用方法, 结合实例形式较为详细的分析了 MediaPlayer 中的常用函数与基本使用技巧, 需要的朋友可以参考下
本文实例讲述了 Android MediaPlayer 基本使用方法。分享给大家供大家参考,具体如下:
使用 MediaPlayer 播放音频或者视频的最简单例子:
Java 代码部分:
- public class MediaPlayerStudy extends Activity {
- private Button bplay,bpause,bstop;
- private MediaPlayer mp = new MediaPlayer();
- @Override
- public void onCreate(BundlesavedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- bplay =(Button)findViewById(R.id.play);
- bpause =(Button)findViewById(R.id.pause);
- bstop =(Button)findViewById(R.id.stop);
- bplay.setOnClickListener(new OnClickListener(){
- @Override
- public void onClick(View v) {
- try {
- mp.setDataSource("/sdcard/test.mp3");
- mp.prepare();
- mp.start();
- } catch (IllegalArgumentException e){
- e.printStackTrace();
- } catch (IllegalStateException e){
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- mp.setOnCompletionListener(new OnCompletionListener(){
- @Override
- public void onCompletion(MediaPlayer mp){
- mp.release();
- }
- });
- }
- });
- bpause.setOnClickListener(new OnClickListener(){
- @Override
- public void onClick(View v) {
- if(mp != null){
- mp.pause();
- }
- }
- });
- bstop.setOnClickListener(new OnClickListener(){
- @Override
- public void onClick(View v) {
- if(mp != null){
- mp.stop();
- }
- }
- });
- }
- @Override
- protected void onDestroy() {
- if(mp != null)
- mp.release();
- super.onDestroy();
- }
- }
布局文件 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">
- <TextView android:layout_width="fill_parent" android:layout_height="wrap_content"
- android:text="@string/hello" />
- <Button android:text="play" android:id="@+id/play" android:layout_width="wrap_content"
- android:layout_height="wrap_content">
- </Button>
- <Button android:text="pause" android:id="@+id/pause" android:layout_width="wrap_content"
- android:layout_height="wrap_content">
- </Button>
- <Button android:text="stop" android:id="@+id/stop" android:layout_width="wrap_content"
- android:layout_height="wrap_content">
- </Button>
- </LinearLayout>
程序说明:
这个例子只是描述了 MediaPlayer 的基本使用步骤和方式,MediaPlayer 还有多种使用方式和方法,并不只局限于例子所介绍的一种。具体来看:
1)如何获得 MediaPlayer 实例:
可以使用直接 new 的方式:
- MediaPlayer mp = new MediaPlayer();
也可以使用 create 的方式,如:
- MediaPlayer mp = MediaPlayer.create(this, R.raw.test);
- //这时就不用调用setDataSource了
2) 如何设置要播放的文件:
来源: http://www.phperz.com/article/17/0826/337600.html