📜  如何在 Android 中构建视频播放器的完整指南(1)

📅  最后修改于: 2023-12-03 15:08:33.224000             🧑  作者: Mango

如何在 Android 中构建视频播放器的完整指南

在移动应用中,视频播放器是非常重要的一部分。在Android平台上,我们可以通过自定义视频播放器来实现更多自定义功能。本指南将为您提供在Android上构建视频播放器的完整指南。

准备工作
  1. 在Android Studio上创建新项目。

  2. 添加以下依赖项:

    dependencies {
        implementation 'com.google.android.exoplayer:exoplayer:2.12.1'
    }
    
  3. 编写布局文件

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    
        <com.google.android.exoplayer2.ui.PlayerView
            android:id="@id/player_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            android:keepScreenOn="true"
            android:visibility="visible"
            app:resize_mode="fill"
            app:surface_type="texture_view" />
    
    </RelativeLayout>
    
加载视频
  1. 创建一个播放器实例:

    private var player: SimpleExoPlayer? = null
    
    private fun initializePlayer() {
        if (player == null) {
            player = SimpleExoPlayer.Builder(context).build()
            playerView.player = player
        }
    }
    
  2. 创建数据源:

    private fun buildMediaSource(uri: Uri): MediaSource {
        return ExtractorMediaSource.Factory(
            DefaultDataSourceFactory(context, "user-agent")
        ).createMediaSource(uri)
    }
    
  3. 加载视频:

    private fun initializePlayer() {
        if (player == null) {
            player = SimpleExoPlayer.Builder(context).build()
            playerView.player = player
            val mediaSource = buildMediaSource(Uri.parse("https://www.example.com/video.mp4"))
            player?.setMediaSource(mediaSource)
            player?.prepare()
        }
    }
    
自定义播放器控件
  1. 创建一个布局文件:

    <?xml version="1.0" encoding="utf-8"?>
    <com.google.android.exoplayer2.ui.PlayerView xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@id/player_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:keepScreenOn="true"
        app:controller_layout_id="@layout/custom_player_control_view" />
    
  2. 创建一个自定义控件:

    class CustomPlayerControlView : FrameLayout, PlayerControlView {
    
        private val binding = CustomPlayerControlBinding.inflate(LayoutInflater.from(context), this, true)
    
        override fun show() {
            isVisible = true
        }
    
        override fun hide() {
            isVisible = false
        }
    
        override fun setPlayer(player: Player?) {}
    
        override fun setVisibilityListener(visibilityListener: PlayerControlView.VisibilityListener?) {}
    
        override fun setControlDispatcher(controlDispatcher: ControlDispatcher?) {}
    
        override fun setRewindIncrementMs(rewindMs: Int) {}
    
        override fun setFastForwardIncrementMs(fastForwardMs: Int) {}
    
        override fun setRepeatToggleModes(repeatToggleModes: Int) {}
    
        override fun getRepeatToggleModes(): Int = REPEAT_TOGGLE_MODE_NONE
    
        override fun setShowMultiWindowTimeBar(show: Boolean) {}
    
        override fun setExtraAdGroupMarkers(extraAdGroupTimesMs: LongArray?, extraPlayedAdGroups: BooleanArray?, adGroupCount: Int) {}
    
        override fun setAspectRatioListener(listener: AspectRatioFrameLayout.AspectRatioListener?) {}
    
        override fun setUseArtwork(useArtwork: Boolean) {}
    
        override fun setErrorMessageProvider(errorMessageProvider: ErrorMessageProvider<in ExoPlaybackException>?) {}
    
        override fun setCustomErrorMessage(customErrorMessage: CharSequence?) {}
    
        override fun setAdGroupTimesMs(adGroupTimesMs: LongArray?, playedAdGroups: BooleanArray?, adGroupCount: Int) {}
    
        override fun setMaxSeekToPreviousPositionMs(maxSeekToPreviousPositionMs: Int) {}
    
        override fun setVisibilityListener(visibilityListener: VisibilityListener?) {}
    
        override fun setPlayWhenReady(playWhenReady: Boolean) {}
    
        override fun setRepeatToggleModes(@RepeatMode repeatToggleModes: Int) {}
    
        override fun setShowShuffleButton(showShuffleButton: Boolean) {}
    
        override fun setPlayer(player: Player) {}
    
        override fun setKeepContentOnPlayerReset(keepContentOnPlayerReset: Boolean) {}
    
        override fun setIsTouching(isTouching: Boolean) {}
    
        override fun setControlDispatcher(controlDispatcher: ControlDispatcher) {}
    
        override fun setFastForwardIncrementMs(fastForwardMs: Int) {}
    
        override fun setShowNextButton(showNextButton: Boolean) {}
    
        override fun setShowPreviousButton(showPreviousButton: Boolean) {}
    
        override fun setRewindIncrementMs(rewindMs: Int) {}
    
        override fun setShowFastForwardButton(showFastForwardButton: Boolean) {}
    
        override fun setExtraAdGroupMarkers(adGroupTimesMs: LongArray?, playedAdGroups: BooleanArray?, adGroupCount: Int, extraAdGroupTimesMs: LongArray?, extraPlayedAdGroups: BooleanArray?, extraAdGroupCount: Int) {}
    
        override fun setShowRewindButton(showRewindButton: Boolean) {}
    
        override fun setShowMultiWindowTimeBar(showMultiWindowTimeBar: Boolean) {}
    
        override fun setAspectRatioListener(listener: AspectRatioListener) {}
    
        override fun setTimeline(timeline: Timeline?) {}
    
        override fun setCustomFastForwardIncrementMs(customFastForwardMs: Long) {}
    
        override fun setCustomRewindIncrementMs(customRewindMs: Long) {}
    
        override fun setUseController(useController: Boolean) {}
    
    }
    

    show()hide()方法中,您可以添加控制视图的逻辑。在布局文件中,您可以设置app:controller_layout_id属性为您创建的自定义控件布局。

集成广告

要在Android中集成视频广告,您可以使用IMA插件。下面是集成视频广告的步骤:

  1. 添加以下依赖项:

    implementation 'com.google.ads.interactivemedia.v3:interactivemedia:4.1.0'
    implementation 'com.google.android.exoplayer:extension-ima:2.12.1'
    
  2. 创建IMA广告加载器:

    private fun createImaAdsLoader(context: Context, adTagUrl: String): AdsLoader {
        return ImaAdsLoader.Builder(context)
            .setAdEventListener(ImaEventListener())
            .setAdUiViewGroup(adViewGroup)
            .setAdDisplayContainer(adDisplayContainer)
            .setAdErrorListener(ImaErrorListener())
            .setAdTagProvider { adTagUrl }
            .build()
    }
    
  3. 加载广告:

    private fun initializePlayer() {
        if (player == null) {
            player = SimpleExoPlayer.Builder(context)
                .setMediaSourceFactory(AdsMediaSourceFactory(context, createImaAdsLoader(context, "https://pubads.g.doubleclick.net/gampad/ads?sz=640x480&" +
                        "iu=/124319096/external/single_ad_samples&ciu_szs=300x250&impl=s&gdfp_req=1&env=vp&output=vast&" +
                        "unviewed_position_start=1&cust_params=deployment%3Ddevsite%26sample_ct%3Dlinear&correlator="))
                .build()
            playerView.player = player
            val mediaSource = buildMediaSource(Uri.parse("https://www.example.com/video.mp4"))
            player?.setMediaSource(mediaSource)
            player?.prepare()
        }
    }
    

    createImaAdsLoader()方法中,您需要更改setAdUiViewGroup()setAdDisplayContainer()方法的参数。在initializePlayer()方法中,您需要更改广告标记URL。

结论

通过本指南,您现在已经知道如何在Android中构建自定义视频播放器,自定义控件以及集成广告,并可以为用户提供更好的体验。有了这些知识,您将能够创建更具有创意和自定义性质的视频播放器。