您的位置:首页 > 移动开发 > Android开发

android从零开始播放视频

2016-05-17 11:02 399 查看
播放视频这个地方我一直有路径问题(捣鼓了太长时间),经过朋友帮助和搜索引擎终于解决,遂记录一下.

首先是视频来源,作为勉强算是半个资深动漫迷...,我选择对bilibili下手,用firefox的插件可以轻松下载b站视频,在附加组件中搜索 NetVideoHunter,第一个蓝色图标的就是,直接下载,然后重启firefox,登录b站,选择一个视频,这里我选择的是秒5(不知道的不用纠结哈哈),打开后点击浏览器新出现的那个蓝色图标,可以发现出现了下载页面,直接下载即可。注意下载下来的格式可能是flv,MediaPlayer不支持,支持mp4和3gp,所以要转码,可以用格式工厂或者优酷自带的转码工具也挺好用。

资源准备好了,接下来是布局文件。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
   <VideoView
       android:id="@+id/video_view"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"/>
 <LinearLayout
     android:layout_width="match_parent"
     android:layout_height="match_parent">
     <Button
         android:id="@+id/play"
         android:layout_width="0dp"
         android:layout_height="wrap_content"
         android:layout_weight="1"
         android:text="开始播放"/>
       <Button
         android:id="@+id/pause"
         android:layout_width="0dp"
         android:layout_height="wrap_content"
         android:layout_weight="1"
         android:text="暂停"/>
        <Button
         android:id="@+id/replay"
         android:layout_width="0dp"
         android:layout_height="wrap_content"
         android:layout_weight="1"
         android:text="重播"/>
     </LinearLayout>
 </LinearLayout>



比较简单,就是一个VideoView下面加两个按钮

接下来是重头戏

public class thirdActivity extends Activity{
private VideoView video;
private Button play;
private Button pause;
private Button replay;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.third_layout);
video=(VideoView)findViewById(R.id.video_view);
video.setVideoPath("android.resource://com.example.b1404030312/"+R.raw.movie);//这里中间(b1404030312)换成自己的包名
play=(Button)findViewById(R.id.play);
play.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (!video.isPlaying())
video.start();
}
});
pause=(Button)findViewById(R.id.pause);
pause.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (video.isPlaying())
video.pause();
}
});
replay=(Button)findViewById(R.id.replay);
replay.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (video.isPlaying())
video.resume();
}
});

}
protected void onDestory()
{
super.onDestroy();
if (video!=null)
video.suspend();
}
}


视频就在res下新建一个raw文件夹将mp4或者3gp的文件移进去,注意最后

R.raw.movie
不需要有后缀名

其实和播放音乐差不多,只不过不需要考虑Service(关了这个页面视频也就结束了,直接在onDestroy中关闭即可,但是按照《第一行代码》书中敲得始终显示视频无法播放,估计是路径问题,所以这边经过询问朋友得知可以采用这种办法,现在播放视屏问题已完美解决.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: