본문 바로가기
안드로이드 웹앱 콘테츠 개발자 양성(국비지원)/Android 기능

Android Studio(기능) 비디오 보여주기VideoView, ExoPlayer

by 차누감 2019. 11. 5.

◎VideoView

ExoPlayer

 

<최종 실행화면>

첫 번째 페이지는 VideoView로 동영상 재생

버튼을 눌렀을 시, 두 번째 페이지는 ExoPlayer로 동영상 재생 (추가로 재생, 일시정지 버튼을 화면 가운데에 배치)

두가지 방법

1)사이트 가져온 동영상 보여주기

2) 내 앱에 있는 동영상 보여주기

 

◎VideoView

1)사이트 가져온 동영상 보여주기

우선 사이트에서 가져온 주소로 동영상을 보여주자. video url 아무거나 가져오면 된다.

 

 

샘플로 이 http 주소를 쓸 것이다.

http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4

화면에 동영상만 나오면 되므로 VideoView만 배치했다.

activity_main.xml 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    tools:context=".MainActivity">
 
    <VideoView
        android:id="@+id/vv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
 
 
</RelativeLayout>
 
 

이제 

MainActivity.java 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
 
 
 
public class MainActivity extends AppCompatActivity {
    VideoView vv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        vv= findViewById(R.id.vv);
        //Video Uri
 
        //비디오뷰의 재생, 일시정지 등을 할 수 있는 '컨트롤바'를 붙여주는 작업
        vv.setMediaController(new MediaController(this));
 
        //VideoView가 보여줄 동영상의 경로 주소(Uri) 설정하기
        vv.setVideoURI(videoUri);
 
        //동영상을 읽어오는데 시간이 걸리므로..
        //비디오 로딩 준비가 끝났을 때 실행하도록..
        //리스너 설정
        vv.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mediaPlayer) {
                //비디오 시작
                vv.start();
            }
        });
 
    }//onCreate ..
 
    //화면에 안보일때...
    @Override
    protected void onPause() {
        super.onPause();
 
        //비디오 일시 정지
        if(vv!=null && vv.isPlaying()) vv.pause();
    }
    //액티비티가 메모리에서 사라질때..
    @Override
    protected void onDestroy() {
        super.onDestroy();
        //
        if(vv!=null) vv.stopPlayback();
    }
}
 
 
 

인터넷에서 동영상 주소를 가져오는 것이므로 퍼미션 등을 줘야한다.

<실행화면>

동영상이 재생되는 것을 볼 수 있다.

추가로 2) 내 앱에 있는 영상 보여주자.

우선 동영상을 넣기위해 raw를 만들어야한다.

내 컴퓨터에 있는 동영상을 raw폴더에 넣자.

기존 코드에서 videoUri 주소 경로만 바꿨다.

<실행화면>

내 프로젝트에 있는 동영상이 재생되는 것을 확인할 수 있다.

ExoPlayer

ExoPlayer를 써보자. 이게 더 편리하다.

기존 코드에서 버튼을 만들어서 버튼을 누를 시 새로운 액티비티를 띄우고, ExoPlayer 방법으로 동영상을 재생하겠다.

버튼을 누르고 새로운 액티비티를 띄우기 위해 액티비티를 만들자.

기존 MainActivity.java에서 clickBtn메소드 안에 내용만 추가하자. ( 새로운 액티비티로 가는 내용)

이제 ExoPlayer를 어떻게 사용하는지 찾는 방법을 알자.

( 나중에 새로운 라이브러리 및 기능을 사용할때 비슷한 경험이 있으면 훨씬 쉽게 찾고 배울 수 있다.)

 

아래 사진에서 자세한 설명은 ExoPlayer를 클릭하면 상세 페이지가 나온다.

새로운 페이지가 나왔는데, 설명을 읽어보면 gradle에 추가하라는 내용이다. 이런 경험이 있어야 나중에 비슷한 작업 쉽다.

새로운 버전을 알기위해 빨간색 글씨를 누르니, git hub페이지가 나오고 새로운 버전 숫자가 써져있다.

이제 버전도 알았으니 gladle에 써주자.

설명 페이지를 또 읽어보면 gradel에 또 추가할 것이 있다.

android 안에 추가해주자.

이제 ExoPlayer 를 사용할 준비가 끝났다.

SecondActivity에 PlaterView를 추가해주자.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
 
 
 
 
public class SecondActivity extends AppCompatActivity {
 
    //video Uri
 
    PlayerView pv;
    //실제 비디오를 플레이하는 객체의 참조 변수
    SimpleExoPlayer player;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
 
        pv=findViewById(R.id.pv);
    }
 
    //화면에 보이기 시작할때!!
    @Override
    protected void onStart() {
        super.onStart();
 
        //SimpleExoPlayer객체 생성
        player= ExoPlayerFactory.newSimpleInstance(thisnew DefaultTrackSelector());
        //플레이어뷰에게 플레이어 설정
        pv.setPlayer(player);
 
        //비디오데이터 소스를 관리하는 DataSource 객체를 만들어주는 팩토리 객체 생성
        DataSource.Factory factory= new DefaultDataSourceFactory(this,"Ex89VideoAndExoPlayer");
        //비디오데이터를 Uri로 부터 추출해서 DataSource객체 (CD or LP판 같은 ) 생성
        ProgressiveMediaSource mediaSource= new ProgressiveMediaSource.Factory(factory).createMediaSource(videoUri);
 
        //만들어진 비디오데이터 소스객체인 mediaSource를
        //플레이어 객체에게 전당하여 준비하도록!![ 로딩하도록 !!]
        player.prepare(mediaSource);
 
        //로딩이 완료되어 준비가 되었을 때
        //자동 실행되도록..
        player.setPlayWhenReady(true);
 
    }
    //화면에 안보일 때..
    @Override
    protected void onStop() {
        super.onStop();
        //플레이어뷰 및 플레이어 객체 초기화
        pv.setPlayer(null);
        player.release();
        player=null;
    }
}
 
 
 

<실행화면>

버튼을 누르면 Exo 라이브러리를 이용하여 동영상이 재생된다.

추가로 여기에 재생과 일시정지 버튼을 화면 가운데에 생성해보자.

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    tools:context=".SecondActivity">
 
        android:id="@+id/pv"
        android:layout_width="match_parent"
        android:layout_height="300dp">
 
        android:id="@+id/pcv"
        android:layout_width="match_parent"
        android:layout_height="300dp"/>
 
</RelativeLayout>
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

이제 재생, 일시정지 표시를 새로운 페이지에 만들어야 한다.

exo_player_control_view.xml 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?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">
 
    <ImageButton
        android:id="@id/exo_play"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_centerInParent="true"
        android:background="#cccc0000"
        style="@style/ExoMediaButton.Play"/>
 
    <ImageButton
        android:id="@id/exo_pause"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_centerInParent="true"
        android:background="#cccc0000"
        style="@style/ExoMediaButton.Pause"/>
 
</RelativeLayout>
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

신기한 것은 이렇게 새로운 xml 파일을 만들고 어디에도 적용하는 코드가 없지만 적용이 된다!!

<실행화면>

첫 번째 페이지는 VideoView로 동영상 재생

버튼을 눌렀을 시, 두 번째 페이지는 ExoPlayer로 동영상 재생 (추가로 재생, 일시정지 버튼을 화면 가운데에 배치)


복붙용 코드

activity_main.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    tools:context=".MainActivity">
 
    <VideoView
        android:id="@+id/vv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
 
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:text="use exoplayer"
        android:onClick="clickBtn"/>
 
 
</RelativeLayout>
 
 

MainActivity.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
 
 
 
public class MainActivity extends AppCompatActivity {
    VideoView vv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        vv= findViewById(R.id.vv);
        //Video Uri
 
 
        //참고 : 내 res 폴더 안에 동영상이  있을 경우
        videoUri= Uri.parse("android.resource://"+getPackageName() + "/"+ R.raw.trailer);
 
 
        //비디오뷰의 재생, 일시정지 등을 할 수 있는 '컨트롤바'를 붙여주는 작업
        vv.setMediaController(new MediaController(this));
 
        //VideoView가 보여줄 동영상의 경로 주소(Uri) 설정하기
        vv.setVideoURI(videoUri);
 
        //동영상을 읽어오는데 시간이 걸리므로..
        //비디오 로딩 준비가 끝났을 때 실행하도록..
        //리스너 설정
        vv.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mediaPlayer) {
                //비디오 시작
                vv.start();
            }
        });
 
    }//onCreate ..
 
    //화면에 안보일때...
    @Override
    protected void onPause() {
        super.onPause();
 
        //비디오 일시 정지
        if(vv!=null && vv.isPlaying()) vv.pause();
    }
    //액티비티가 메모리에서 사라질때..
    @Override
    protected void onDestroy() {
        super.onDestroy();
        //
        if(vv!=null) vv.stopPlayback();
    }
 
    public void clickBtn(View view) {
        startActivity(new Intent(this,SecondActivity.class));
        finish();
    }
}
 
 
 

activity_second.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    tools:context=".SecondActivity">
 
        android:id="@+id/pv"
        android:layout_width="match_parent"
        android:layout_height="300dp">
 
        android:id="@+id/pcv"
        android:layout_width="match_parent"
        android:layout_height="300dp"/>
 
</RelativeLayout>
 
 

SecondActivity.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
 
 
 
 
public class SecondActivity extends AppCompatActivity {
 
    //video Uri
 
    PlayerView pv;
    //실제 비디오를 플레이하는 객체의 참조 변수
    SimpleExoPlayer player;
 
    //컨트롤러 뷰 참조 변수
    PlayerControlView pcv;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
 
        pv=findViewById(R.id.pv);
        pcv=findViewById(R.id.pcv);
    }
 
    //화면에 보이기 시작할때!!
    @Override
    protected void onStart() {
        super.onStart();
 
        //SimpleExoPlayer객체 생성
        player= ExoPlayerFactory.newSimpleInstance(thisnew DefaultTrackSelector());
        //플레이어뷰에게 플레이어 설정
        pv.setPlayer(player);
        //플레이어 컨트럴뷰와 플레이어 연동
        pcv.setPlayer(player);
 
        //비디오데이터 소스를 관리하는 DataSource 객체를 만들어주는 팩토리 객체 생성
        DataSource.Factory factory= new DefaultDataSourceFactory(this,"Ex89VideoAndExoPlayer");
        //비디오데이터를 Uri로 부터 추출해서 DataSource객체 (CD or LP판 같은 ) 생성
        ProgressiveMediaSource mediaSource= new ProgressiveMediaSource.Factory(factory).createMediaSource(videoUri);
 
        //만들어진 비디오데이터 소스객체인 mediaSource를
        //플레이어 객체에게 전당하여 준비하도록!![ 로딩하도록 !!]
        player.prepare(mediaSource);
 
        //로딩이 완료되어 준비가 되었을 때
        //자동 실행되도록..
        //player.setPlayWhenReady(true);
 
    }
    //화면에 안보일 때..
    @Override
    protected void onStop() {
        super.onStop();
        //플레이어뷰 및 플레이어 객체 초기화
        pv.setPlayer(null);
        player.release();
        player=null;
    }
}
 
 
 

exo_player_control_view.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?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">
 
    <ImageButton
        android:id="@id/exo_play"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_centerInParent="true"
        android:background="#cccc0000"
        style="@style/ExoMediaButton.Play"/>
 
    <ImageButton
        android:id="@id/exo_pause"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_centerInParent="true"
        android:background="#cccc0000"
        style="@style/ExoMediaButton.Pause"/>
 
</RelativeLayout>
 
 

댓글