Android VideoView

In this tutorial, we’ll learn about Android VideoView. We will create an android app in Android Studio and play video from URL, we will also do some customizations to it’s control panel.

在本教程中,我们将学习Android VideoView。 我们将在Android Studio中创建一个android应用并从URL播放视频,我们还将对其控制面板进行一些自定义。

Android VideoView (Android VideoView)

Android VideoView class is used to display Video files in them. Following are the acceptable formats:

Android VideoView类用于在其中显示视频文件。 以下是可接受的格式:

  • 3gp

    3gp
  • MP4 – Only H.263, H.264, H.264 codecs work.

    MP4 –仅H.263,H.264,H.264编解码器有效。

VideoViews can play videos either from resource files, local data or url specified. Following are some of the methods used on VideoView:

VideoView可以播放来自资源文件,本地数据或指定URL的视频。 以下是VideoView上使用的一些方法:

  • setVideoURI() – This is used to set the url path. It needs to be parsed as a URI.

    setVideoURI()–用于设置URL路径。 它需要解析为URI。
  • setVideoPath() – Used for local paths.

    setVideoPath()–用于本地路径。
  • start()

    开始()
  • stopPlayback()

    stopPlayback()
  • seekTo(int milliSec)

    seekTo(int milliSec)
  • pause()

    暂停()
  • resume()

    恢复()
  • isPlaying()

    正在玩()
  • canPause()

    canPause()
  • canSeekForward()

    canSeekForward()
  • canSeekBackward()

    canSeekBackward()
  • setOnCompletedListener()

    setOnCompletedListener()
  • addSubtitleSource()

    addSubtitleSource()
  • setMediaController() : Used to add MediaControls on the Video. Pause/Play, Seek

    setMediaController():用于在视频上添加MediaControls。 暂停/播放,搜寻
  • getDuration()

    getDuration()
  • setOnPreparedListener() : Gets invoked once the video starts.

    setOnPreparedListener():视频开始播放后调用。

Note: VideoView does not retain its full state when going into the background.

注意:进入背景时,VideoView不会保留其完整状态。

In the following section, we’ll be creating an application that runs Videos from urls one after the other.
We’ll see how the MediaController works with the VideoView.

在下一节中,我们将创建一个应用程序,该应用程序一个接一个地运行来自url的视频。
我们将看到MediaController如何与VideoView

Android VideoView示例 (Android VideoView Example)

Do not forget to add the Internet Permission in your AndroidManifest.xml file.

不要忘记在您的AndroidManifest.xml文件中添加Internet权限。

Android VideoView示例代码 (Android VideoView Example Code)

activity_main.xml

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.journaldev.videoview.MainActivity">
    
    <TextView
        android:id="@+id/txtPlaceholder"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/videoView"
        android:layout_centerHorizontal="true"
        android:layout_margin="16dp"
        android:text="DOUBLE TAP TO VIEW CONTROLS"
        android:textStyle="bold" />


    <VideoView
        android:id="@+id/videoView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true" />

</RelativeLayout>

MainActivity.java (MainActivity.java)

The code for the MainActivity.java looks like this:

MainActivity.java的代码如下所示:

package com.journaldev.videoview;

import android.media.MediaPlayer;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.MediaController;
import android.widget.Toast;
import android.widget.VideoView;
import java.util.ArrayList;
import java.util.Arrays;

public class MainActivity extends AppCompatActivity {

    VideoView videoView;
    ArrayList<String> arrayList = new ArrayList<>(Arrays.asList("https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4", "https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4"));

    int index = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        videoView = findViewById(R.id.videoView);
        final MediaController mediacontroller = new MediaController(this);
        mediacontroller.setAnchorView(videoView);


        videoView.setMediaController(mediacontroller);
        videoView.setVideoURI(Uri.parse(arrayList.get(index)));
        videoView.requestFocus();

        videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                Toast.makeText(getApplicationContext(), "Video over", Toast.LENGTH_SHORT).show();
                if (index++ == arrayList.size()) {
                    index = 0;
                    mp.release();
                    Toast.makeText(getApplicationContext(), "Video over", Toast.LENGTH_SHORT).show();
                } else {
                    videoView.setVideoURI(Uri.parse(arrayList.get(index)));
                    videoView.start();
                }


            }
        });
        
        videoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                Log.d("API123", "What " + what + " extra " + extra);
                return false;
            }
        });
    }
}

We’ve added two urls in an ArrayList. We set the anchorView() on the VideoView to keep the MediaControl inside the VideoView.

我们在ArrayList中添加了两个URL。 我们在VideoView上设置anchorView() ,以将MediaControl保留在VideoView

The output looks something like this:

输出看起来像这样:

MediaControl为什么在VideoView之外? (Why is the MediaControl outside the VideoView?)

Well, the MediaControl doesn’t know the dimensions of the VideoView until the video is started.

好吧,在视频开始播放之前,MediaControl才知道VideoView的尺寸。

For having media control inside the video, we need to set the onPreparedListener on our VideoView and then set the anchor inside it. This way the MediaController is set inside the VideoView.

为了在视频内部拥有媒体控制权,我们需要在VideoView上设置onPreparedListener ,然后在其中设置锚点。 这样,可以在VideoView内部设置MediaController。

Our updated MainActivity.java class looks like this now:

我们更新后的MainActivity.java类现在看起来像这样:

package com.journaldev.videoview;

import android.media.MediaPlayer;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.MediaController;
import android.widget.Toast;
import android.widget.VideoView;
import java.util.ArrayList;
import java.util.Arrays;

public class MainActivity extends AppCompatActivity {

    VideoView videoView;
    ArrayList<String> arrayList = new ArrayList<>(Arrays.asList("https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4", "https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4"));
    int index = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        videoView = findViewById(R.id.videoView);
        final MediaController mediacontroller = new MediaController(this);
        mediacontroller.setAnchorView(videoView);


        videoView.setMediaController(mediacontroller);
        videoView.setVideoURI(Uri.parse(arrayList.get(index)));
        videoView.requestFocus();

        videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mp.setOnVideoSizeChangedListener(new MediaPlayer.OnVideoSizeChangedListener() {
                    @Override
                    public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
                        videoView.setMediaController(mediacontroller);
                        mediacontroller.setAnchorView(videoView);

                    }
                });
            }
        });

        videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                Toast.makeText(getApplicationContext(), "Video over", Toast.LENGTH_SHORT).show();
                if (index++ == arrayList.size()) {
                    index = 0;
                    mp.release();
                    Toast.makeText(getApplicationContext(), "Videos completed", Toast.LENGTH_SHORT).show();
                } else {
                    videoView.setVideoURI(Uri.parse(arrayList.get(index)));
                    videoView.start();
                }


            }
        });

        videoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                Log.d("API123", "What " + what + " extra " + extra);
                return false;
            }
        });
    }
}

mp.release() is set to release the media player resources. It should be done to prevent memory leaks. Any videoView calls after this line would lead to a CRASH.

mp.release()设置为释放媒体播放器资源。 应该这样做以防止内存泄漏 。 此行之后的任何videoView调用都将导致CRASH。

Now the output of the above application in action is given below:

android studio videoview tutorial

现在,上面应用程序的输出如下:

This brings an end to android video view tutorial. You can download the final Android VideoView project from the link below.

这就结束了android video view tutorial。 您可以从下面的链接下载最终的Android VideoView项目。

翻译自: https://www.journaldev.com/20671/android-videoview

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值