Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

안드로이드 앱에서 YouTube 동영상 재생하는 방법, 단계별 예제로 배우기

안드로이드 앱에서 YouTube 동영상 재생하기

이 튜토리얼은 안드로이드 애플리케이션에서 YouTube 동영상을 재생하는 방법을 단계별로 보여줍니다. RecyclerView와 WebView를 조합하여 여러 개의 YouTube 영상을 스크롤 가능한 목록 형태로 재생하는 예제입니다.

1단계 — 새 프로젝트 생성

Android Studio에서 File → New Project를 선택해 새 프로젝트를 만들고, 필요한 항목을 모두 입력합니다.

2단계 — build.gradle에 의존성 추가

build.gradle(Module: app) 파일에 아래 의존성을 추가합니다.

implementation 'com.android.support:recyclerview-v7:28.0.0'
implementation 'com.android.support:cardview-v7:28.0.0'

3단계 — activity_main.xml 레이아웃 작성

res/layout/activity_main.xml 파일에 다음 코드를 추가합니다.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16sp"
    tools:context=".MainActivity">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </android.support.v7.widget.RecyclerView>

</RelativeLayout>

4단계 — 비디오 항목 레이아웃 생성

새 레이아웃 리소스 파일(video_view.xml)을 만들고 다음 코드를 추가합니다. 각 목록 항목은 WebView 하나로 구성됩니다.

<?xml version="1.0" encoding="utf-8"?>
<WebView xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/webView"
    android:layout_width="match_parent"
    android:layout_height="180dp">
</WebView>

5단계 — youTubeVideos.java 데이터 클래스 생성

동영상 URL을 담는 데이터 모델 클래스를 만들고 다음 코드를 작성합니다.

public class youTubeVideos {
    String videoUrl;

    public youTubeVideos() {
    }

    public youTubeVideos(String videoUrl) {
        this.videoUrl = videoUrl;
    }

    public String getVideoUrl() {
        return videoUrl;
    }

    public void setVideoUrl(String videoUrl) {
        this.videoUrl = videoUrl;
    }
}

6단계 — VideoAdapter.java 어댑터 작성

RecyclerView 어댑터 클래스를 만들어 각 항목의 WebView에 iframe 형식의 YouTube 임베드 코드를 로드합니다. 이때 자바스크립트 실행을 반드시 허용해야 정상적으로 재생됩니다.

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import java.util.List;

public class VideoAdapter extends RecyclerView.Adapter<VideoAdapter.VideoViewHolder> {

    private List<youTubeVideos> youtubeVideoList;

    VideoAdapter(List<youTubeVideos> youtubeVideoList) {
        this.youtubeVideoList = youtubeVideoList;
    }

    @Override
    public VideoViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.video_view, parent, false);
        return new VideoViewHolder(view);
    }

    @Override
    public void onBindViewHolder(VideoViewHolder holder, int position) {
        holder.videoWeb.loadData(
                youtubeVideoList.get(position).getVideoUrl(),
                "text/html", "utf-8");
    }

    @Override
    public int getItemCount() {
        return youtubeVideoList.size();
    }

    class VideoViewHolder extends RecyclerView.ViewHolder {
        WebView videoWeb;

        VideoViewHolder(View itemView) {
            super(itemView);
            videoWeb = itemView.findViewById(R.id.webView);
            videoWeb.getSettings().setJavaScriptEnabled(true);
            videoWeb.setWebChromeClient(new WebChromeClient() {});
        }
    }
}

7단계 — MainActivity.java 작성

메인 액티비티에서 Vector에 YouTube iframe 문자열들을 담고 어댑터에 연결합니다. src 속성의 동영상 ID만 바꾸면 원하는 영상을 자유롭게 교체할 수 있습니다.

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import java.util.Vector;

public class MainActivity extends AppCompatActivity {

    RecyclerView recyclerView;
    Vector<youTubeVideos> youtubeVideos = new Vector<>();

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

        recyclerView = findViewById(R.id.recyclerView);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        youtubeVideos.add(new youTubeVideos("<iframe width=\"100%\" height=\"100%\" src=\"https://www" + ".youtube.com/embed/eWEF1Zrmdow\" frameborder=\"0\" allowfullscreen></iframe>"));
        youtubeVideos.add(new youTubeVideos("<iframe width=\"100%\" height=\"100%\" src=\"https://www" + ".youtube.com/embed/KyJ71G2UxTQ\" frameborder=\"0\" allowfullscreen></iframe>"));
        youtubeVideos.add(new youTubeVideos("<iframe width=\"100%\" height=\"100%\" src=\"https://www" + ".youtube.com/embed/y8Rr39jKFKU\" frameborder=\"0\" allowfullscreen></iframe>"));
        youtubeVideos.add(new youTubeVideos("<iframe width=\"100%\" height=\"100%\" src=\"https://www" + ".youtube.com/embed/8Hg1tqIwIfI\" frameborder=\"0\" allowfullscreen></iframe>"));
        youtubeVideos.add(new youTubeVideos("<iframe width=\"100%\" height=\"100%\" src=\"https://www" + ".youtube.com/embed/uhQ7mh_o_cM\" frameborder=\"0\" allowfullscreen></iframe>"));

        VideoAdapter videoAdapter = new VideoAdapter(youtubeVideos);
        recyclerView.setAdapter(videoAdapter);
    }
}

8단계 — AndroidManifest.xml 권한 설정

영상을 인터넷에서 스트리밍하므로 매니페스트에 네트워크 관련 권한을 반드시 선언해야 합니다.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="app.com.sample">

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>

    </application>
</manifest>

앱 실행하기

이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤 툴바의 Run 아이콘을 클릭하세요. 목록에서 본인의 모바일 기기를 선택하면, 기기 화면에 아래와 같이 YouTube 동영상 목록이 표시됩니다.

안드로이드 앱에서 YouTube 동영상 재생하는 방법, 단계별 예제로 배우기