1. 程式人生 > >Android中利用VideoView播放網路上視訊的基礎用法

Android中利用VideoView播放網路上視訊的基礎用法

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"/>