본문 바로가기

Unity

[Unity] 안드로이드 갤러리에서 비디오 선택 후 재생하기

유니티에서 안드로이드 폰의 갤러리에서 비디오를 불러와 재생하는 방법이다.

 

 

1. UnityNativeGallery 유니티 패키지 다운로드 후 설치

https://github.com/yasirkula/UnityNativeGallery

 

GitHub - yasirkula/UnityNativeGallery: A native Unity plugin to interact with Gallery/Photos on Android & iOS (save and/or load

A native Unity plugin to interact with Gallery/Photos on Android & iOS (save and/or load images/videos) - GitHub - yasirkula/UnityNativeGallery: A native Unity plugin to interact with Gallery/P...

github.com

 

 

2. 코드 작성

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.IO;
using UnityEngine.Video;

public class playVideo : MonoBehaviour {

	public VideoPlayer vp;
	public RawImage videoDisplay; //비디오 화면을 표시할 RawImage

	
    public void PlayVideo() {
    	
        //사진과 동영상들 중 선택 가능
    	NativeGallery.GetMixedMediaFromGallery((media) => {
                FileInfo selectedMedia = new FileInfo(media);

                if (!string.IsNullOrEmpty(media)) {
                
                	//mp4 파일을 불러오고 싶은 경우
                    if (media.Substring(media.Length - 3, 3) == "mp4")
                        StartCoroutine(LoadVideo(media));
                }
            }, NativeGallery.MediaType.Image | NativeGallery.MediaType.Video);
    
    }
    
    
    IEnumerator LoadVideo(string videoPath)
    {
        yield return null;
        
        //선택한 경로의 비디오 파일 읽기
        var tempVideo = File.ReadAllBytes(videoPath);

        if (vp == null)
            vp = gameObject.AddComponent<VideoPlayer>();

	//VideoPlayer에 소스 비디오 지정
        vp.url = videoPath;
        vp.source = VideoSource.Url;

	//비디오 화면을 표시할 videoDisplay의 texture를 VideoPlayer의 targetTexture로 지정
        videoDisplay.texture = vp.targetTexture;

        vp.Prepare();

        while (!vp.isPrepared)
            yield return null;

	//재생
        vp.Play();
    }


}

 

 

3. 비디오 렌더링을 위한 Render Texture 생성 후 Size(가로 x 세로 해상도) 지정

 

 

4. 해당 스크립트를 붙인 오브젝트에 Video Player 컴포넌트 추가. Target Texture를 위에서 생성한 Render Texture로 지정

 

 

5. 스크립트의 VideoPlayer와 RawImage 지정

 

 

 

LIST