视频播放入门1

Android多媒体(Media)入门

18 NOV


本讲内容:Android中的音频和视频使用入门指南

Android 提供了 MediaPlayer 和 MediaRecorder 两个工具类,来帮助开发者操作音频和视频。我们通过两个小例子来学习一下多媒体资源的使用。

一、 简单音乐播放器

1、新建一个项目Lesson28_Music , 主Activity的名字是 MainMusic.java

2、拷贝 play_50 play_disable pause_50 pause_disable stop_50 stop_disable 这几张图片到res/drawable目录下,并建立3个xml文件,拷贝love.mp3到res/raw文件中。

play.xml

1 <?xml version="1.0" encoding="utf-8"?>
2 <selector xmlns:android="http://schemas.android.com/apk/res/android">
3     <item android:drawable="@drawable/play_disable" android:state_enabled="false"><!-- state_enabled=false -->
4     <item android:drawable="@drawable/play_50"<!-- default -->
5 </item></item></selector>

pause.xml

1 <?xml version="1.0" encoding="utf-8"?>
2 <selector xmlns:android="http://schemas.android.com/apk/res/android">
3     <item android:drawable="@drawable/pause_disable"android:state_enabled="false"<!-- state_enabled=false -->
4     <item android:drawable="@drawable/pause_50"<!-- default -->
5 </item></item></selector>

stop.xml

1 <?xml version="1.0" encoding="utf-8"?>
2 <selector xmlns:android="http://schemas.android.com/apk/res/android">
3     <item android:drawable="@drawable/stop_disable" android:state_enabled="false"><!-- state_enabled=false -->
4     <item android:drawable="@drawable/stop_50"<!-- default -->
5 </item></item></selector>

3、res/layout/main.xml 的内容如下:

01 <?xml version="1.0" encoding="utf-8"?>
02 <linearlayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical" android:layout_width="fill_parent"android:layout_height="fill_parent">
03     <textview android:layout_width="fill_parent"android:layout_height="wrap_content" android:textsize="25sp" android:text="简单音乐播放器">
04          
05     </textview></linearlayout><linearlayoutxmlns:android="http://schemas.android.com/apk/res/android"android:orientation="horizontal" android:layout_width="fill_parent"android:layout_height="fill_parent">
06          
07         <imagebutton android:layout_width="wrap_content"android:layout_height="wrap_content" android:layout_margin="4dp"android:adjustviewbounds="true" android:id="@+id/play"android:background="@drawable/play">
08         </imagebutton>
09
10         <imagebutton android:layout_width="wrap_content"android:layout_height="wrap_content" android:layout_margin="4dp"android:adjustviewbounds="true" android:id="@+id/pause"android:background="@drawable/pause">
11         </imagebutton>
12          
13         <imagebutton android:layout_width="wrap_content"android:layout_height="wrap_content" android:layout_margin="4dp"android:adjustviewbounds="true" android:id="@+id/stop"android:background="@drawable/stop">
14         </imagebutton>
15     </linearlayout>

4、MainMusic.java的内容如下:

001 package android.basic.lesson28;
002
003 import java.io.IOException;
004
005 import android.app.Activity;
006 import android.media.MediaPlayer;
007 import android.media.MediaPlayer.OnCompletionListener;
008 import android.media.MediaPlayer.OnPreparedListener;
009 import android.os.Bundle;
010 import android.view.View;
011 import android.view.View.OnClickListener;
012 import android.widget.ImageButton;
013 import android.widget.Toast;
014
015 public class MainMusic extends Activity {
016
017     // 声明变量
018     private ImageButton play, pause, stop;
019     private MediaPlayer mPlayer;
020
021     /** Called when the activity is first created. */
022     @Override
023     public void onCreate(Bundle savedInstanceState) {
024         super.onCreate(savedInstanceState);
025         setContentView(R.layout.main);
026
027         // 定义UI组件
028         play = (ImageButton) findViewById(R.id.play);
029         pause = (ImageButton) findViewById(R.id.pause);
030         stop = (ImageButton) findViewById(R.id.stop);
031
032         // 按钮先全部失效
033         play.setEnabled(false);
034         pause.setEnabled(false);
035         stop.setEnabled(false);
036
037         // 定义单击监听器
038         OnClickListener ocl = new View.OnClickListener() {
039
040             @Override
041             public void onClick(View v) {
042                 switch (v.getId()) {
043                 case R.id.play:
044                     // 播放
045                     Toast.makeText(MainMusic.this"点击播放", Toast.LENGTH_SHORT)
046                             .show();
047                     play();
048                     break;
049                 case R.id.pause:
050                     // 暂停
051                     Toast.makeText(MainMusic.this"暂停播放", Toast.LENGTH_SHORT)
052                             .show();
053                     pause();
054                     break;
055                 case R.id.stop:
056                     // 停止
057                     Toast.makeText(MainMusic.this"停止播放", Toast.LENGTH_SHORT)
058                             .show();
059                     stop();
060                     break;
061                 }
062             }
063         };
064
065         // 绑定单击监听
066         play.setOnClickListener(ocl);
067         pause.setOnClickListener(ocl);
068         stop.setOnClickListener(ocl);
069
070         // 初始化
071         initMediaPlayer();
072     }
073
074     // 初始化播放器
075     private void initMediaPlayer() {
076
077         // 定义播放器
078         mPlayer = MediaPlayer.create(getApplicationContext(), R.raw.love);
079
080         // 定义资源准备好的监听器
081         mPlayer.setOnPreparedListener(new OnPreparedListener() {
082             @Override
083             public void onPrepared(MediaPlayer mp) {
084                 // 资源准备好了再让播放器按钮有效
085                 Toast.makeText(MainMusic.this"onPrepared", Toast.LENGTH_SHORT)
086                         .show();
087                 play.setEnabled(true);
088             }
089         });
090
091         // 定义播放完成监听器
092         mPlayer.setOnCompletionListener(new OnCompletionListener() {
093
094             @Override
095             public void onCompletion(MediaPlayer mp) {
096                 Toast.makeText(MainMusic.this"onCompletion",
097                         Toast.LENGTH_SHORT).show();
098                 stop();
099             }
100         });
101     }
102
103     // 停止播放
104     private void stop() {
105         mPlayer.stop();
106         pause.setEnabled(false);
107         stop.setEnabled(false);
108         try {
109             mPlayer.prepare();
110             mPlayer.seekTo(0);
111             play.setEnabled(true);
112         catch (IllegalStateException e) {
113             e.printStackTrace();
114         catch (IOException e) {
115             e.printStackTrace();
116         }
117
118     }
119
120     // 播放
121     private void play() {
122
123         mPlayer.start();
124         play.setEnabled(false);
125         pause.setEnabled(true);
126         stop.setEnabled(true);
127     }
128
129     // 暂停
130     private void pause() {
131         mPlayer.pause();
132         play.setEnabled(true);
133         pause.setEnabled(false);
134         stop.setEnabled(true);
135     }
136
137     // Activity销毁前停止播放
138     @Override
139     protected void onDestroy() {
140         super.onDestroy();
141         if (stop.isEnabled()) {
142             stop();
143         }
144
145     }
146
147 }

5、运行程序,查看效果

image

image

二、简单视频播放器

Android为视频播放提供了VideoView 和 MediaController 两个现成的组件,让我们可以方便的实现MP4、3GP等视频的播放。下面我们通过一个例子来看一下:

1、新建一个项目 Lesson28_Video

2、使用 Format Factory 这个软件压缩一个视频备用,我这里压缩的参数如下:

image

注意,如果播放时完全无法播放或者只有声音没有图像,你就需要换压缩软件和调整压缩参数重新压缩视频了,暂时只能这样,我也是折腾了2-3小时都是黑屏,郁闷中(似乎得出一个答案,是否黑屏和机器设备的性能有关,我降低压缩分辨率和每秒帧数,出图像音画同步,如果提高每秒帧数,声音出来后十几秒图像才会出来,但是出来后音画还是同步的,有兴趣的朋友可以多测试测试给出一个结论)。

用命令行的方式拷贝此视频到存储卡(sdcard)中,为什么不用eclipse中的可视化工具拷贝呢?因为那个方式靠大文件的时候经常失败,而命令行方式我没拷贝失败一次过。命令就是 adb push ,具体截个图给你看:

image

3、res\layout\main.xml的内容如下:

1 <?xml version="1.0" encoding="utf-8"?>
2 <linearlayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical" android:layout_width="match_parent"android:layout_height="match_parent" android:layout_gravity="top">
3 <videoview android:layout_width="fill_parent" android:layout_height="fill_parent"android:id="@+id/VideoView01">
4 </videoview>
5 </linearlayout>

4、MainVideo.java的内容如下:

01 package android.basic.lesson28;
02
03 import android.app.Activity;
04 import android.net.Uri;
05 import android.os.Bundle;
06 import android.view.Window;
07 import android.view.WindowManager;
08 import android.widget.MediaController;
09 import android.widget.VideoView;
10
11 public class MainVideo extends Activity {
12     /** Called when the activity is first created. */
13     @Override
14     public void onCreate(Bundle savedInstanceState) {
15         super.onCreate(savedInstanceState);
16         //全屏
17         this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
18         //标题去掉
19         this.requestWindowFeature(Window.FEATURE_NO_TITLE);
20         //要在全屏等设置完毕后再加载布局
21         setContentView(R.layout.main);
22
23         //定义UI组件
24         VideoView videoView = (VideoView) findViewById(R.id.VideoView01);
25         //定义MediaController对象
26         MediaController mediaController = new MediaController(this);
27         //把MediaController对象绑定到VideoView上
28         mediaController.setAnchorView(videoView);
29         //设置VideoView的控制器是mediaController
30         videoView.setMediaController(mediaController);
31          
32         //这两种方法都可以 videoView.setVideoPath("file:///sdcard/love_480320.mp4");
33         videoView.setVideoURI(Uri.parse("/sdcard/love_480320.mp4"));
34         //启动后就播放
35         videoView.start();
36     }
37 }

5、运行效果如下:

image

image

三、简单录音程序

1、新建一个一个项目 Tip_Recorder,主activity名字是  MainActivity

2、其布局文件main.xml的代码是:

1 <?xml version="1.0" encoding="utf-8"?>
2 <linearlayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical" android:layout_width="fill_parent"android:layout_height="fill_parent" android:gravity="center">
3
4     <button android:layout_width="wrap_content"android:layout_height="wrap_content" android:textsize="30sp" android:text="录音"android:id="@+id/Button01"></button>
5     <button android:layout_width="wrap_content"android:layout_height="wrap_content" android:textsize="30sp" android:text="停止"android:id="@+id/Button02" android:layout_margintop="20dp"></button>
6 </linearlayout>

3、主程序文件 MainActivity.java的代码如下:

01 package android.tip.yaoyao;
02
03 import java.io.File;
04 import java.io.IOException;
05 import java.util.Calendar;
06 import java.util.Locale;
07
08 import android.app.Activity;
09 import android.media.MediaRecorder;
10 import android.os.Bundle;
11 import android.text.format.DateFormat;
12 import android.view.View;
13 import android.widget.Button;
14 import android.widget.Toast;
15
16 public class MainActivity extends Activity {
17
18     private Button recordButton;
19     private Button stopButton;
20
21     private MediaRecorder mr;
22
23
24     @Override
25     public void onCreate(Bundle savedInstanceState) {
26         super.onCreate(savedInstanceState);
27         setContentView(R.layout.main);
28
29         recordButton = (Button) this.findViewById(R.id.Button01);
30         stopButton = (Button) this.findViewById(R.id.Button02);
31
32         // 录音按钮点击事件
33         recordButton.setOnClickListener(new View.OnClickListener() {
34
35             @Override
36             public void onClick(View v) {
37
38                 File file = new File("/sdcard/"
39                         "YY"
40                         new DateFormat().format("yyyyMMdd_hhmmss",
41                                 Calendar.getInstance(Locale.CHINA)) + ".amr");
42
43                 Toast.makeText(getApplicationContext(), "正在录音,录音文件在"+file.getAbsolutePath(), Toast.LENGTH_LONG)
44                         .show();
45
46                 // 创建录音对象
47                 mr = new MediaRecorder();
48
49                 // 从麦克风源进行录音
50                 mr.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
51
52                 // 设置输出格式
53                 mr.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
54
55                 // 设置编码格式
56                 mr.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
57
58                 // 设置输出文件
59                 mr.setOutputFile(file.getAbsolutePath());
60
61                 try {
62                     // 创建文件
63                     file.createNewFile();
64                     // 准备录制
65                     mr.prepare();
66                 catch (IllegalStateException e) {
67                     e.printStackTrace();
68                 catch (IOException e) {
69                     e.printStackTrace();
70                 }
71                 // 开始录制
72                 mr.start();
73                 recordButton.setText("录音中……");
74             }
75         });
76
77         // 停止按钮点击事件
78         stopButton.setOnClickListener(new View.OnClickListener() {
79
80             @Override
81             public void onClick(View v) {
82
83                 if (mr != null) {
84                     mr.stop();
85                     mr.release();
86                     mr = null;
87                     recordButton.setText("录音");
88                     Toast.makeText(getApplicationContext(), "录音完毕", Toast.LENGTH_LONG).show();
89                 }
90             }
91         });
92
93     }
94
95 }

4、因为录音和写存储卡都需要权限声明,所以这里也把AndroidManifest.xml代码提供出来:

01 <?xml version="1.0" encoding="utf-8"?>
02 <manifest xmlns:android="http://schemas.android.com/apk/res/android"android:versionname="1.0" android:versioncode="1" package="android.tip.yaoyao">
03     <application android:debuggable="true" android:label="@string/app_name"android:icon="@drawable/icon">
04         <activity android:label="@string/app_name"android:configchanges="orientation|keyboardHidden|keyboard"android:screenorientation="portrait" android:name=".MainActivity">
05             <intent -filter="">
06                 <action android:name="android.intent.action.MAIN">
07                 <category android:name="android.intent.category.LAUNCHER">
08             </category></action></intent>
09         </activity>
10
11     </application>
12     <uses -sdk="" android:minsdkversion="4">
13
14
15 <uses -permission="" android:name="android.permission.RECORD_AUDIO"></uses>
16 <uses -permission="" android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses>
17 </uses></manifest>

 

5、编译并运行程序,查看结果。

image

点击录音:

image

录音文件在存储卡的根目录几个以YY开头的amr文件

image

6、这个例子要用到录音设备,而模拟器并不能把电脑声卡模拟出来使用,因此这个例子必须在真机上进行测试。 真机上测试方法也很简单。

  1. 在真机上把USB调试模式打开,
  2. 把真机用USB线与电脑连接
  3. 设置电脑和手机的连接方式为 ”仅充电“(此时手机可以操作存储卡)
  4. 打开Eclipse,在不选择模拟器的情况下运行程序,此时,Eclipse会自动找到真机,并使用它运行程序,最完美的是他可以把真机运行程序的输出信息,照样输出在Eclipse中的Logcat日志中。


上面的真机截图也是通过Eclipse的DDMS窗口直接抓取的,下图中右上角颜色最深的图标就是抓取真机截图的按钮:

未命名

好了本讲内容就到这里,下次再见。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值