본문 바로가기
안드로이드 자바

[JAVA][Android] Media3 사용해서 동영상 재생하기

by teamnova 2024. 7. 2.

안녕하세요.

오늘은 안드로이드에서 제공하는 Media3 를 사용해서 기기에 저장된 동영상을 불러와 재생하는 예제입니다.

 

Media3는 기존에 많이 사용했던 ExoPlayer 라이브러리를 대체하는 미디어 플레이어 라이브러리입니다.

해당 라이브러리에 대한 자세한 내용은 아래 공식 문서를 참고해주세요.

https://developer.android.com/media/media3?hl=ko

 

Jetpack Media3 소개  |  Android media  |  Android Developers

이 페이지는 Cloud Translation API를 통해 번역되었습니다. Jetpack Media3 소개 컬렉션을 사용해 정리하기 내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요. Jetpack Media3은 Android 앱이 풍부한 오디

developer.android.com

 

 

1. 의존성 추가

이 글에서는 간단한 조작이 가능한 Media3 ExoPlayer를 사용합니다.

다음과 같이 앱 수준의 build.gradle에 의존성을 항목을 추가합니다.  

implementation "androidx.media3:media3-exoplayer:1.3.1"
implementation "androidx.media3:media3-exoplayer-dash:1.3.1"
implementation "androidx.media3:media3-ui:1.3.1"

 

 

2. 레이아웃 작성

activity_main.xml
<androidx.constraintlayout.widget.ConstraintLayout 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"
    tools:context=".MainActivity">

    <!-- 비디오 선택 버튼 -->
    <Button
        android:id="@+id/button_select_video"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="비디오 선택"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        android:layout_marginTop="20dp"/>

    <!-- 비디오 재생을 위한 PlayerView -->
    <androidx.media3.ui.PlayerView
        android:id="@+id/player_view"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintTop_toBottomOf="@id/button_select_video"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginTop="20dp"/>
</androidx.constraintlayout.widget.ConstraintLayout>

 

 

3. 메인 액티비티 작성

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.media3.common.MediaItem;
import androidx.media3.exoplayer.ExoPlayer;
import androidx.media3.ui.PlayerView;

public class MainActivity extends AppCompatActivity {

    private ExoPlayer player; // ExoPlayer 객체 선언
    private PlayerView playerView; // PlayerView 객체 선언
    private Uri selectedVideoUri; // 선택된 비디오의 URI를 저장할 변수

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 레이아웃에서 버튼과 PlayerView를 연결
        Button buttonSelectVideo = findViewById(R.id.button_select_video);
        playerView = findViewById(R.id.player_view);

        // 비디오 선택 버튼 클릭 시 실행될 리스너 설정
        buttonSelectVideo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectVideo(); // 비디오 선택 함수 호출
            }
        });
    }

    // ActivityResultLauncher를 사용하여 비디오 선택 결과를 처리
    private final ActivityResultLauncher<Intent> videoPickerLauncher = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(),
            result -> {
                if (result.getResultCode() == RESULT_OK && result.getData() != null) {
                    // 비디오가 성공적으로 선택된 경우
                    selectedVideoUri = result.getData().getData();
                    if (selectedVideoUri != null) {
                        initializePlayer(selectedVideoUri); // 플레이어 초기화 및 비디오 재생
                    } else {
                        Toast.makeText(this, "Failed to get video URI", Toast.LENGTH_SHORT).show();
                    }
                }
            });

    // 비디오 선택 인텐트를 시작하는 함수
    private void selectVideo() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
        videoPickerLauncher.launch(intent);
    }

    // ExoPlayer를 초기화하고 선택된 비디오를 재생하는 함수
    private void initializePlayer(Uri videoUri) {
        if (player == null) {
            // ExoPlayer 빌더를 사용하여 ExoPlayer 객체 생성
            player = new ExoPlayer.Builder(this).build();
            playerView.setPlayer(player); // PlayerView에 ExoPlayer 설정
        }

        // 비디오 URI를 사용하여 MediaItem 생성
        MediaItem mediaItem = MediaItem.fromUri(videoUri);
        player.setMediaItem(mediaItem); // ExoPlayer에 MediaItem 설정
        player.prepare(); // ExoPlayer 준비
        player.play(); // 비디오 재생 시작
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (player != null) {
            player.release(); // ExoPlayer 해제
            player = null;
        }
    }
}

 

 

4. 시연 영상

위 코드를 실행하면 다음 영상과 같이 보여집니다.