Memory

[ANDROID/KOTLIN] ExoPlayer로 동영상 실행하기 (r2.12.2) 본문

IT/ANDROID

[ANDROID/KOTLIN] ExoPlayer로 동영상 실행하기 (r2.12.2)

_JinHa_ 2021. 1. 12. 21:48
반응형

ExoPlayer 공식 홈페이지

exoplayer.dev/hello-world.html

 

Hello world! - ExoPlayer

 

exoplayer.dev

XML

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".activity.VideoDetailActivity">

    <FrameLayout
        android:id="@+id/frameL_video_detail"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <!-- 기본
             빨리감기 / 되감기 : 15초
         -->
        <com.google.android.exoplayer2.ui.PlayerView
            android:id="@+id/exoPlayerV_video_detail"
            android:layout_width="match_parent"
            android:layout_height="250dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent"/>

        <!-- Custom
             show_timeout : PlayerView사용자가 마지막으로 상호 작용 한 후 컨트롤이 숨겨지기 전까지의 지연 시간
             빨리감기(fastforward_increment) / 되감기(rewind_increment) : 30초
        -->
        <com.google.android.exoplayer2.ui.PlayerView
            android:id="@+id/exoPlayerV_video_detail"
            android:layout_width="match_parent"
            android:layout_height="250dp"
            app:show_timeout="10000"
            app:fastforward_increment="30000"
            app:rewind_increment="30000"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent"/>
    </FrameLayout>
    
    ...
    
</LinearLayout

 

CODE ( ViewBinding 사용중 )

class VideoDetailActivity : AppCompatActivity() {
    private lateinit var mBinding: ActivityVideoDetailBinding

    private var player: SimpleExoPlayer? = null
    private var playWhenReady = true
    private var currentWindow = 0
    private var playbackPosition = 0L

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mBinding = ActivityVideoDetailBinding.inflate(layoutInflater)
        setContentView(mBinding.root)

        mContext = this@VideoDetailActivity
    }

    fun initializePlayer() {

        val sample = "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4"
        val sample2 = "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4"

        if (player == null) {
            player = SimpleExoPlayer.Builder(this).build()
            mBinding.exoPlayerVVideoDetail.player = player
            mBinding.exoPlayerVVideoDetail.controllerShowTimeoutMs = 0
        }

        /**
         * 1개 영상 실행할 때
         * */
        val mediaSource: MediaSource = buildMediaSource(Uri.parse(sample))
        player?.setMediaSource(mediaSource)

        /**
         * 재생목록 만들기 (다음 영상 추가)
         * */
         
        // 첫번째로 실행할 영상
        val mediaItem = MediaItem.fromUri(sample)
        player?.setMediaItem(mediaItem)
        // 두번째로 실행할 영상
        val secondMediaItem = MediaItem.fromUri(sample2)
        player?.addMediaItem(secondMediaItem)


        player?.playWhenReady = playWhenReady
        player?.seekTo(currentWindow, playbackPosition)
        player?.prepare()
    }

    fun buildMediaSource(uri: Uri): MediaSource {
        val userAgent: String = Util.getUserAgent(this, "project_name")
        return if (uri.lastPathSegment!!.contains("mp3") || uri.lastPathSegment!!.contains("mp4")) {
            ProgressiveMediaSource.Factory(DefaultHttpDataSourceFactory(userAgent))
                .createMediaSource(
                    MediaItem.fromUri(uri)
                )
        } else if (uri.lastPathSegment!!.contains("m3u8")) {
            HlsMediaSource.Factory(DefaultHttpDataSourceFactory(userAgent)).createMediaSource(
                MediaItem.fromUri(uri)
            )
        } else {
            ProgressiveMediaSource.Factory(DefaultDataSourceFactory(this, userAgent))
                .createMediaSource(
                    MediaItem.fromUri(uri)
                )
        }
    }

    fun releasePlayer() {
        player?.let {
            playWhenReady = it.playWhenReady
            playbackPosition = it.currentPosition
            currentWindow = it.currentWindowIndex
            it.release()
            player = null
        }
    }

    @SuppressLint("InlinedApi")
    private fun hideSystemUi() {
        mBinding.exoPlayerVVideoDetail.systemUiVisibility = (
                    View.SYSTEM_UI_FLAG_LOW_PROFILE
                    or View.SYSTEM_UI_FLAG_FULLSCREEN
                    or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                    or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                )
    }

    override fun onStart() {
        super.onStart()
        if (Util.SDK_INT >= 24) {
            initializePlayer()
        }
    }

    override fun onResume() {
        super.onResume()
        // hideSystemUi() -> 전체화면 환경으로 만들기
        hideSystemUi()
        if ((Util.SDK_INT < 24 || player == null)) {
            initializePlayer()
        }
    }

    override fun onPause() {
        super.onPause()
        if (Util.SDK_INT < 24) {
            releasePlayer()
        }
    }

    override fun onStop() {
        super.onStop()
        if (Util.SDK_INT >= 24) {
            releasePlayer()
        }
    }
}

 

 

 

[참고]

 

출처 -

Media streaming with ExoPlayer

developer.android.com/codelabs/exoplayer-intro#0

 

Media streaming with ExoPlayer  |  Android 개발자  |  Android Developers

In this codelab, you build a media player to render audio and adaptive video streams with ExoPlayer, the open source media player running in the Android YouTube app. The codelab uses and customizes the UI components included with the library and demonstrat

developer.android.com

 

무작정 앱만들기-6 (ExoPlayer로 간단한 뮤직 플레이어를 만들어보자)

medium.com/@sunminlee89/%EB%AC%B4%EC%9E%91%EC%A0%95-%EC%95%B1%EB%A7%8C%EB%93%A4%EA%B8%B0-6-exoplayer%EB%A1%9C-%EA%B0%84%EB%8B%A8%ED%95%9C-%EB%AE%A4%EC%A7%81-%ED%94%8C%EB%A0%88%EC%9D%B4%EC%96%B4%EB%A5%BC-%EB%A7%8C%EB%93%A4%EC%96%B4%EB%B3%B4%EC%9E%90-46e6b2594601

 

무작정 앱만들기-6(ExoPlayer로 간단한 뮤직 플레이어를 만들어보자)

이번 포스팅의 최종 목표 화면

medium.com

안드로이드) ExoPlayer2 사용법

rlg1133.tistory.com/58

 

안드로이드) Exoplayer2 사용법

allprojects { repositories { google() jcenter() } } 제일먼저 project경로의 그래들 파일에 위와같이 추가해준다. android { compileOptions { sourceCompatibility 1.8 targetCompatibility 1.8 } } 그리고 ap..

rlg1133.tistory.com

여러 개의 영상을 Exoplayer로 순차 재상하기

medium.com/hongbeomi-dev/%EC%97%AC%EB%9F%AC-%EA%B0%9C%EC%9D%98-%EC%98%81%EC%83%81%EC%9D%84-exoplayer%EB%A1%9C-%EC%88%9C%EC%B0%A8-%EC%9E%AC%EC%83%9D%ED%95%98%EA%B8%B0-e04025321b2f

 

여러 개의 영상을 Exoplayer로 순차 재생하기

What is ExoPlayer?

medium.com

 

반응형