1. 程式人生 > >第二十四篇-用VideoView製作一個簡單的視訊播放器

第二十四篇-用VideoView製作一個簡單的視訊播放器

這是一個播放本地視訊的播放器,videoUrl1是手機裡放置視訊的路徑

效果圖:

MainActivity.java

package com.example.aimee.videotest;

import android.Manifest;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle; import android.view.WindowManager; import android.widget.MediaController; import android.widget.Toast; import android.widget.VideoView; public class MainActivity extends AppCompatActivity { private final int REQUESTCODE=101; private VideoView videoView; @Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.layout); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.M){
int checkSelfPermission=checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE); if(checkSelfPermission== PackageManager.PERMISSION_DENIED){ requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},REQUESTCODE); } } play_mp4(); } private void play_mp4(){ String videoUrl1 = "/storage/emulated/0/save/a1.mp4"; Uri uri = Uri.parse( videoUrl1 ); videoView = (VideoView)this.findViewById(R.id.videoView ); videoView.setMediaController(new MediaController(this)); videoView.setVideoURI(uri); videoView.start(); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults){ super.onRequestPermissionsResult(requestCode,permissions,grantResults); if(requestCode==REQUESTCODE){ if (permissions[0].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE) && grantResults[0]== PackageManager.PERMISSION_GRANTED){ Toast.makeText(this,"ok", Toast.LENGTH_LONG).show(); }else { Toast.makeText(this,"無許可權",Toast.LENGTH_LONG).show(); } } } }
View Code

 

layout.xml

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

    <VideoView
        android:id="@+id/videoView"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
         />
</LinearLayout>
View Code

 

androidmanifest.xml中要新增許可權

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

 

注意:使用模擬器播放時,要確保路徑下有那個視訊。從電腦傳視訊到模擬器的方法在上一篇中有。不過,每次傳完當時可以用,不過重啟電腦或重啟模擬器時,那個視訊檔案會丟失,所以下次想用時得重新上傳。我是用的ADV tools裡面建立的模擬器,不知道其他模擬器會不會同樣如此。