android exoplayer在您的应用中播放视频,例如youtube

视频应用程序的重要性(The Importance of Video Apps)

There’s a constant need for video-playing apps for entertainment, educational, and many other purposes. You can see it clearly if we look at Youtube usage over the past five to ten years. Even in most remote areas of the globe, mobile entertainment increased a lot. Even illiterate people in remote villages are using video apps for entertainment purposes. On the other hand, thanks to the pandemic caused by COVID-19, most schools across the world are turning to E-Learning. For these reasons, there’s a lot that can be done by one good application, built to serve the hunger of the current world. Enough talk, let’s dive into our concept: Exoplayer.

持续需要用于娱乐,教育和许多其他目的的视频播放应用程序。 如果我们查看过去五到十年的Youtube使用情况,您可以清楚地看到它。 即使在全球大多数偏远地区,移动娱乐也大大增加了。 甚至偏远乡村的文盲也都在使用视频应用来娱乐。 另一方面,由于COVID-19引起的大流行,全球大多数学校都在转向电子学习。 由于这些原因,一个好的应用程序可以完成很多工作,这些应用程序可以满足当前世界的饥饿需求。 聊够了,让我们深入探讨一下我们的概念:Exoplayer。

介绍 (Introduction)

Before the ExoPlayer Android’s MediaPlayer API is the main solution for playing audio and video both locally and over the Internet across Android devices. At the start, playing a simple video using MediaPlayer was easy but if you wanted to build a player like Youtube it would take a great deal of time, effort, and pain. My rule is to not reinvent the wheel — instead, use the perfect solution that’s already available.

在使用ExoPlayer之前,Android的MediaPlayer API是在本地以及通过Android设备通过Internet播放音频和视频的主要解决方案。 刚开始时,使用MediaPlayer播放简单的视频很容易,但是如果您想构建一个类似Youtube的播放器,将需要大量的时间,精力和痛苦。 我的原则是不要重新发明轮子,而是使用已经可用的完美解决方案。

ExoPlayer is the video player running in the Android YouTube app. It’s not part of the Android framework — it’s an open-source project maintained by Google. ExoPlayer is a library provided by Google that handles audio and video-related things on our behalf and we can call few methods to play with it. We can also make our own customization to the player UI (User Interface).

ExoPlayer是在Android YouTube应用中运行的视频播放器。 它不是Android框架的一部分,而是Google维护的一个开源项目。 ExoPlayer是Google提供的一个库,它代表我们处理与音频和视频有关的事情,我们可以调用几种方法来玩它。 我们还可以对播放器UI(用户界面)进行自定义。

ExoPlayer was built on the top of Android’s MediaCodec API, which was out in Android 4.1 (API level 16). So, if we want to integrate Exoplayer the minimum API version needs to be set to API 16 for your apps.

ExoPlayer建立在Android的MediaCodec API的顶部,而后者在Android 4.1(API级别16)中已经发布。 因此,如果我们要集成Exoplayer,则需要为您的应用将最低API版本设置为API 16。

为什么要使用ExoPlayer? (Why use ExoPlayer?)

  • ExoPlayer supports features like DASH (Dynamic Adaptive Streaming over HTTP), HLS(HTTP Live Streaming), SmoothStreaming, and Common Encryption, which are not supported by MediaPlayer.

    ExoPlayer支持DASH(HTTP上的动态自适应流),HLS(HTTP实时流),SmoothStreaming和Common Encryption等功能,而MediaPlayer不支持这些功能。

  • ExoPlayer has a modular design so it’s easily extended and customized.

    ExoPlayer具有模块化设计,因此可以轻松扩展和定制。
  • The major Video Streaming giants on Android mostly depend on Exoplayer because of its features and flexibility. ExoPlayer is the video player running in Android YouTube, Netflix, Amazon media player for Prime, HotStar, and many other popular and robust apps.

    Android上的主要视频流巨人由于其功能和灵活性而大多依赖Exoplayer。 ExoPlayer是运行在Android YouTube,Netflix,Amazon Prime,HotStar和许多其他流行且功能强大的应用程序的亚马逊媒体播放器中的视频播放器。
  • Good documentation and tutorials.

    好的文档和教程。
  • It’s free!

    免费!

Enough talk, let’s get coding.

聊够了,让我们开始编码。

基本的Android ExoPlayer应用 (Basic Android ExoPlayer App)

Let’s check the integration by creating a sample app and checking the step-by-step procedure for gain a better understanding. Create a new project from your studio and follow steps below.

让我们通过创建一个示例应用程序并检查分步过程来获得更好的理解,从而检查集成。 在您的工作室中创建一个新项目,然后执行以下步骤。

If you don’t have enough time to go step-by-step, or you intend to dive in to the code directly, check out the repo link of the sample integration:

如果您没有足够的时间逐步进行操作,或者打算直接深入研究代码,请查看示例集成的回购链接:

步骤1:在应用程序级别的build.gradle文件中添加ExoPlayer依赖项 (Step 1: Add ExoPlayer dependency in the app-level build.gradle file)

implementation 'com.google.android.exoplayer:exoplayer:2.11.8'

This can be of any version you choose — I just added the latest version available at that moment. By the way, we also have the flexibility of adding only the library modules that we actually need, rather than the complete pack mentioned above.

它可以是您选择的任何版本-我刚刚添加了当时可用的最新版本。 顺便说一下,我们还可以灵活地只添加我们实际需要的库模块,而不必添加上面提到的完整包。

implementation 'com.google.android.exoplayer:exoplayer-core:2.X.X'
implementation 'com.google.android.exoplayer:exoplayer-dash:2.X.X'
implementation 'com.google.android.exoplayer:exoplayer-ui:2.X.X'

The available library modules are :

可用的库模块为:

  • exoplayer-core: Core functionality (mandatory).

    exoplayer-core :核心功能(强制性)。

  • exoplayer-dash: Support for DASH content.

    exoplayer-dash :支持DASH内容。

  • exoplayer-hls: Support for HLS content.

    exoplayer-hls :支持HLS内容。

  • exoplayer-smoothstreaming: Support for SmoothStreaming content.

    exoplayer-smoothstreaming :支持exoplayer-smoothstreaming内容。

  • exoplayer-ui: UI components and resources for use with ExoPlayer.

    exoplayer-ui :与ExoPlayer一起使用的UI组件和资源。

In this example, let’s follow by adding a complete pack because adding individual modules has different requirements and can sometimes cause errors.

在此示例中,让我们接着添加一个完整的包,因为添加单个模块有不同的要求,有时会导致错误。

Also, make sure you’ve added JCenter and Google in the repositories section of your project level build.gradle file, although they’re added by default in the newer version.

另外,请确保已在repositories添加了JCenter和Google 项目级别的build.gradle文件中的“部分”,尽管它们是默认情况下在较新版本中添加的。

repositories {google()
jcenter()
}

步骤2:在应用程序级别build.gradle启用Java8支持 (Step 2: Enable Java8 support in the app level build.gradle)

compileOptions {targetCompatibility JavaVersion.VERSION_1_8}

步骤3:创建XML并将ExPlayer View添加到其中 (Step 3: Create an XML and add ExPlayer View to it)

To customize the UI to look like Youtube or something else we need to add some layouts, drawables, etc, which we will see in my upcoming articles. Here, let’s inflate the basic PlayerView:

要自定义用户界面以使其看起来类似于Youtube或其他内容,我们需要添加一些布局,可绘制对象等,我们将在我的后续文章中看到它们。 在这里,让我们为基本的PlayerView充气:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">


    <com.google.android.exoplayer2.ui.PlayerView
        android:id="@+id/video_player_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>


</androidx.constraintlayout.widget.ConstraintLayout>

步骤4:通过创建ExoPlayer实例并分配要播放的源来初始化播放器(Step 4: Initialize the Player by Creating an Instance of ExoPlayer and Assigning a Source to Play)

As we are done with the UI, let’s create the instance of ExoPlayer to start playing the media. We can use the available builder pattern to create the instance. In most cases using SimpleExoPlayer would be a convenient way to do it — the implementation of the ExoPlayer interface.

完成UI的操作后,让我们创建ExoPlayer的实例以开始播放媒体。 我们可以使用可用的构建器模式来创建实例。 在大多数情况下,使用SimpleExoPlayer将是一种方便的方法ExoPlayer接口的实现。

val videoPlayer = SimpleExoPlayer.Builder(this).build()

As we’ve created the instance of ExoPlayer, we now need to assign it to the view created in XML:

创建ExoPlayer实例后,现在需要将其分配给以XML创建的视图:

video_player_view?.player = videoPlayer

Next, we need to build the source to play. There are many types of MediaSource’s available — let's start with ProgressiveMediaSource. Here let's take a URL and play it by building ProgressiveMediaSource.

接下来,我们需要构建播放源。 有多种类型的MediaSource可用-让我们从ProgressiveMediaSource开始 在这里,让我们采用一个URL并通过构建ProgressiveMediaSource播放它

This is generally done in two steps. In the first step we create the instance of DefaultDataSourceFactory and then pass this instance to the ProgressiveMediaSource.Factory, as below:

这通常分两个步骤完成。 在第一步中,我们创建DefaultDataSourceFactory的实例 然后将此实例传递给ProgressiveMediaSource.Factory ,如下所示:

private fun buildMediaSource(): MediaSource? {
        val dataSourceFactory = DefaultDataSourceFactory(this, "sample")
        return ProgressiveMediaSource.Factory(dataSourceFactory)
            .createMediaSource(Uri.parse(sampleUrl))
    }

sampleUrl is a string variable that contains the streaming URL.

sampleUrl是包含流URL的字符串变量。

By now the initialize player method will look like this:

现在,初始化播放器方法将如下所示:

private fun initializePlayer() {
        videoPlayer = SimpleExoPlayer.Builder(this).build()
        video_player_view?.player = videoPlayer
        buildMediaSource()?.let {
            videoPlayer?.prepare(it)
        }
    }

步骤5:添加与活动生命周期相关的基本暂停和播放功能(Step 5: Add Basic Pause and Play Functionality Relating to the Activities Lifecycle)

When we’re done, don’t forget to release the player:

完成后,请不要忘记释放播放器:

override fun onResume() {
        super.onResume()
        videoPlayer?.playWhenReady = true
    }


    override fun onStop() {
        super.onStop()
        videoPlayer?.playWhenReady = false
        if (isFinishing) {
            releasePlayer()
        }
    }


    private fun releasePlayer() {
        videoPlayer?.release()
    }

步骤6:将Internet权限添加到清单文件并运行应用程序(Step 6: Add the Internet Permission to the Manifest File and Run the App)

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

You should see the video playing below with all the player functionalities: Pause, play, rewind, and seek options, etc.

您应该在下面看到具有播放器所有功能的视频播放:暂停,播放,快退和查找选项等。

Image for post
The video was trimmed due to larger size
由于尺寸较大,视频被剪裁

The whole activity will look something like this:

整个活动将如下所示:

package com.sample.exoplayer


import android.net.Uri
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.google.android.exoplayer2.SimpleExoPlayer
import com.google.android.exoplayer2.source.MediaSource
import com.google.android.exoplayer2.source.ProgressiveMediaSource
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory
import kotlinx.android.synthetic.main.activity_main.*




class MainActivity : AppCompatActivity() {
    private var videoPlayer: SimpleExoPlayer? = null
    private var sampleUrl = "https://www.learningcontainer.com/wp-content/uploads/2020/05/sample-mp4-file.mp4"


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        initializePlayer()
    }




    private fun buildMediaSource(): MediaSource? {
        val dataSourceFactory = DefaultDataSourceFactory(this, "sample")
        return ProgressiveMediaSource.Factory(dataSourceFactory)
            .createMediaSource(Uri.parse(sampleUrl))
    }


    private fun initializePlayer() {
        videoPlayer = SimpleExoPlayer.Builder(this).build()
        video_player_view?.player = videoPlayer
        buildMediaSource()?.let {
            videoPlayer?.prepare(it)
        }
    }


    override fun onResume() {
        super.onResume()
        videoPlayer?.playWhenReady = true
    }


    override fun onStop() {
        super.onStop()
        videoPlayer?.playWhenReady = false
        if (isFinishing) {
            releasePlayer()
        }
    }


    private fun releasePlayer() {
        videoPlayer?.release()
    }
}

This player would work with functionality similar to YouTube. When the app goes to the background the player pauses playing, when the user comes back it plays from where it had stopped.

该播放器可以使用类似于YouTube的功能。 当应用程序进入后台时,播放器会暂停播放,而当用户返回时,它将从停止位置播放。

But in real-world scenarios, we need to handle many more things for a better user experience, like state handling of the player or holding the seek position to resume.

但是在现实世界中,我们需要处理更多事情以获得更好的用户体验,例如玩家的状态处理或保持寻找位置以恢复。

Here’s the repo link of GitHub for the sample used in this article:

这是本文中使用的示例的GitHub的repo链接:

概要 (Summary)

That’s all, for now. I hope you learned something new. Let’s check the advanced state handling, Live stream handling, beautification of UI similar to Youtube, etc in my upcoming articles. Stay tuned!

目前为止就这样了。 希望您学到了新东西。 在我即将发表的文章中,让我们检查高级状态处理,实时流处理,类似于Youtube的UI美化等。 敬请关注!

Please leave me your suggestions and comments.

请给我您的建议和意见。

Thanks for reading.

谢谢阅读。

翻译自: https://medium.com/better-programming/android-exoplayer-play-videos-in-your-app-like-youtube-486853913397

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值