LoginSignup
11

More than 5 years have passed since last update.

AndroidでYoutubeの動画を再生する

Posted at

はじめに

YoutubeAPIよくわからんし、AndroidでYoutube動画流す方法が分からずにいたところ、動画再生ライブラリのExoPlayerに触れる過程で出来たので載せておきます。

さっそくやってみる

準備

ExoPlayer2.9.0を使いました。

build.gradle
dependencies {
    ...

    //ExoPlayer
    implementation "com.google.android.exoplayer:exoplayer-core:${EXOPLAYER_VERSION}"
    implementation "com.google.android.exoplayer:exoplayer-dash:${EXOPLAYER_VERSION}"
    implementation "com.google.android.exoplayer:exoplayer-hls:${EXOPLAYER_VERSION}"
    implementation "com.google.android.exoplayer:exoplayer-ui:${EXOPLAYER_VERSION}"
}
gradle.properties
EXOPLAYER_VERSION=2.9.0

Permissionの設定も忘れないようにします。

AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"/>

レイアウト

SurfaceViewでもいいのですが、今回はExoPlayerに搭載されてるPlayerViewを使いました。

main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    <com.google.android.exoplayer2.ui.PlayerView
            android:id="@+id/player_view"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:background="#000000"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toEndOf="parent"/>

</android.support.constraint.ConstraintLayout>

動画を流す

通信速度を計測してくれるExoPlayerのインターフェースのインスタンスを作成しておきます。

val bandwidthMeter: DefaultBandwidthMeter by lazy {
        DefaultBandwidthMeter()
    }

ExoPlayerインスタンスの初期化をします。ここで上記インスタンスも渡します。

val exoPlayer: ExoPlayer? by lazy {
        ExoPlayerFactory.newSimpleInstance(
            context,
            DefaultTrackSelector(AdaptiveTrackSelection.Factory(bandwidthMeter))
        )
    }

次に流したい動画の.m3u8ファイルURLを取得します。
取得方法はこちらの記事で紹介しています。

取得した.m3u8ファイルURL文字列をURI形式に変換します。

val uri = Uri.parse("https ... .m3u8")

データを読み込みます。
ここで通信速度の変化のリスナーをセットできるのですが、今回は割愛します。

val dataSourceFactory =
            DefaultDataSourceFactory(context, Util.getUserAgent(context, "ExoPlayerSample"), bandwidthMeter)

 exoPlayer?.prepare(HlsMediaSource(uri, dataSourceFactory, null, null))

最後にExoPlayerをViewにセットしてplayWhenReadyをTrueにすることで再生されます。

val playerView: PlayerView = findViewById(R.id.player_view)
playerView.player = exoPlayer

exoPlayer?.playWhenReady = true

動画が再生されたかと思います。
device-2019-01-19-191238.png

さいごに

コードはGitHubに上げてます。
ExoPlayerSample

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11