Android中利用VideoView播放网络上视频的基础用法

来源:互联网 发布:淘宝香港代购好的店铺 编辑:程序博客网 时间:2024/06/02 06:30

Demo:


代码:

主活动为LocalVideoActivity

package com.example.playvideotest;import android.media.MediaPlayer;import android.net.Uri;import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.widget.MediaController;import android.widget.Toast;import android.widget.VideoView;public class LocalVideoActivity extends AppCompatActivity {    private VideoView videoview ;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        //本地的视频 需要在手机SD卡根目录添加一个Demo.mp4 视频       // String videoUrl1 = Environment.getExternalStorageDirectory().getPath()+"/Demo.mp4" ;        //网络视频            videoview = (VideoView)this.findViewById(R.id.video_view );        //设置视频控制器        videoview.setMediaController(new MediaController(this));        //播放完成回调        videoview.setOnCompletionListener( new MyPlayerOnCompletionListener());        //设置视频路径        //videoView.setVideoURI(uri);        videoview.setVideoPath("http://172.28.6.100/item/video/Y02_01.mp4");        //开始播放视频        videoview.start();    }    class MyPlayerOnCompletionListener implements MediaPlayer.OnCompletionListener {        @Override        public void onCompletion(MediaPlayer mp) {            Toast.makeText( LocalVideoActivity.this, "播放完成了", Toast.LENGTH_SHORT).show();        }    }}
注:上述Demo中 .mp4格式的视频是在PC服务器端存放,自己需要换成自己可访问的url

主布局activity_main.xml

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    tools:context="com.example.playvideotest.LocalVideoActivity">    <RelativeLayout        android:layout_width="match_parent"        android:layout_height="200dp">        <VideoView            android:id="@+id/video_view"            android:layout_width="match_parent"            android:layout_height="match_parent"            />    </RelativeLayout></RelativeLayout>

最后由于需要访问网络,Androidmanifest.xml中加入访问权限的声明

  <uses-permission android:name="android.permission.INTERNET" />    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>


原创粉丝点击