천천히 , 강하게 멀리

안드로이드 ExoPlayer2 사용법. Kotlin 본문

Android/Kotlin

안드로이드 ExoPlayer2 사용법. Kotlin

힌새 2020. 4. 23. 17:40
allprojects {
    repositories {
        google()
        jcenter()
    }
}

 

build.gradle 프로젝트 경로에 이렇게 추가를 해준다.

 

 

compileOptions {
    targetCompatibility JavaVersion.VERSION_1_8
}

 

build.gradle app 경로에 추가한다.

ExoPlayer 는 자바 8을 사용하기 때문에 사용할수 있게 해준다.

 

implementation 'com.google.android.exoplayer:exoplayer:2.10.5'
implementation 'com.google.android.exoplayer:exoplayer-core:2.10.5'
implementation 'com.google.android.exoplayer:exoplayer-dash:2.10.5'
implementation 'com.google.android.exoplayer:exoplayer-ui:2.10.5'
implementation 'com.google.android.exoplayer:exoplayer-hls:2.10.5'

build.gradle app 경로에 있는 dependencies 에 라이브러리를 추가해준다.

 

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

액티비티 레이아웃에 SimpleExoPlayerView를 추가한다.

 

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

 

ExoPlayer 변수들을 액티비티에 선언해준다.

 

    override fun onStop() {
        super.onStop()
        releasePlayer()
    }
    private fun initializePlayer() {
        if (player == null) {
            player = ExoPlayerFactory.newSimpleInstance(this.applicationContext)
            //플레이어 연결
            ExoplayerView?.player = player
        }

        val mediaSource: MediaSource = this.buildMediaSource(selectedvideo!!)!!
        //prepare
        player!!.prepare(mediaSource, true, false)
        //start,stop
        player!!.playWhenReady = playWhenReady
    }
    private fun buildMediaSource(uri: Uri): MediaSource? {
        val userAgent: String = Util.getUserAgent(this, "Take Notes")
        return if (uri.lastPathSegment!!.contains("mp3") || uri.lastPathSegment!!.contains("mp4")) {
            ProgressiveMediaSource.Factory(DefaultHttpDataSourceFactory(userAgent))
                .createMediaSource(uri)
        } else if (uri.lastPathSegment!!.contains("m3u8")) { //com.google.android.exoplayer:exoplayer-hls 확장 라이브러리를 빌드 해야 합니다.
            ProgressiveMediaSource.Factory(DefaultHttpDataSourceFactory(userAgent))
                .createMediaSource(uri)
        } else {
            ProgressiveMediaSource.Factory(DefaultDataSourceFactory(this, userAgent))
                .createMediaSource(uri)
        }
    }

    private fun releasePlayer() {
        if (player != null) {
            playbackPosition = player!!.currentPosition
            currentWindow = player!!.currentWindowIndex
            playWhenReady = player!!.playWhenReady
            ExoplayerView?.player = null
            player!!.release()
            player = null
        }
    }

 

액티비티 onCreate함수 밑에 위 코드를 작성한다

비디오를 실행하고싶은 위치에 initializePlayer() 함수를 넣어주면 동영상이 실행이 된다.

'Android > Kotlin' 카테고리의 다른 글

안드로이드 ExoPlayer2 전체화면 만들기.  (0) 2020.04.24