티스토리 뷰

반응형

ExoPlayer2

ExoPlayer는 안드로이드용 미디어 플레이어로, 로컬 및 인터넷의 음성, 영상 파일들을 재생할 수 있다. 안드로이드 내장 기능인 MediaPlayer API에서 제공하는것들 뿐만 아니라 추가 기능들도 지원하는데, 사용할때 별도의 복잡한 설정 없이 커스터마이징하거나 상속할 수 있어서 매우 편리하다.

 

실제로 YouTube앱도 ExoPlayer를 사용해서 구현했다고!

 

기능별 지원하는 형식(mp4, avi...)은 모두 이 링크에서 확인할 수 있다.

 

 

 

 

설정

build.gradle(project)의 레포지토리에 두 개 다 있는지 확인

repositories {
    google()
    jcenter()
}

 

build.gradle(:app)에 추가

dependencies {
    implementation 'com.google.android.exoplayer:exoplayer:2.10.6'
}

최신 버전 확인은 여기서 하면 된다. 

 

 

 

 

실행 코드

activity_video.xml

    <com.google.android.exoplayer2.ui.PlayerView
        android:id="@+id/exoPlayerView"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:resize_mode="fill"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

xml파일에 추가해주고

 

 

VideoActivity.kt

simpleExoPlayer = ExoPlayerFactory.newSimpleInstance(this, DefaultTrackSelector())
exoPlayerView.player = simpleExoPlayer

URI = "http://www. ...스트리밍 주소 여기 넣기"

val factory: DataSource.Factory = DefaultDataSourceFactory(this, "ExoPlayer")
val mediaSource: ProgressiveMediaSource = ProgressiveMediaSource.Factory(factory).createMediaSource(URI)
simpleExoPlayer.prepare(mediaSource)
simpleExoPlayer.playWhenReady = true

코틀린 파일에 onCreate()시 이렇게 써주면 완성이다.

 

 

 

 

처음에는 잘 작동되다가 에러가 자꾸 나는 경우

override fun onDestroy() {
    super.onDestroy()
    simpleExoPlayer.release()
}

 

자원 release를 해주지 않으면 처음엔 재생이 잘 되는데 연속적으로 몇 개 이상의 영상을 시청할 경우, 다음 영상이 안켜지는 에러가 난다. 이런 에러가 나지 않으려면 필수적으로 자원 해제를 해줘야한다. 여기서는 액티비티가 종료될때 해제해줬다.

 

 

 

 

영상의 상태 변화에 리스너 달아주기

simpleExoPlayer.addListener(object : Player.EventListener {
    /**
     * @param playWhenReady - Whether playback will proceed when ready.
     * @param playbackState - One of the STATE constants.
     */
    override fun onPlayerStateChanged(
        playWhenReady: Boolean,
        playbackState: Int
    ) {
        when (playbackState) {
            Player.STATE_IDLE -> {
            	
            }
            Player.STATE_BUFFERING -> {
            
            }
            Player.STATE_READY -> {
            
            }
            Player.STATE_ENDED -> {
            
            }
            else -> {
            
            }
        }
    }
})

영상이 끝날때를 감지해서 실행됐으면 하는 코드를 Player.STATE_ENDED에 넣어주면 된다.

 

 

 

참고 링크

- 구글에서 제공하는 코드랩 

 

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

- 공식문서

 

Hello world! - ExoPlayer

 

exoplayer.dev

- 레포 주소

 

google/ExoPlayer

An extensible media player for Android. Contribute to google/ExoPlayer development by creating an account on GitHub.

github.com

 

 

반응형