2022-09-28

ExpoのManaged Workflowでreact-native-videoのExoPlayerを使う設定

v5以下でのExoPlayerを使うための設定

react-native-videoのv5系でExoPlayerを使うための設定です。

ExoPlayerはメディアを再生するためのAndroid用のライブラリです。react-native-videoのv6ではデフォルトでExoPlayerが使われるようになりますが、v5以下ではデフォルトでMediaPlayerが使われるため、ExoPlayerを使うには設定を変更する必要があります。

素のReact Nativeプロジェクト(Bare Workflow)の場合、react-native.config.jsで以下の設定を追加するか、

module.exports = {
  ...
  dependencies: {
    'react-native-video': {
      platforms: {
        android: {
          sourceDir: '../node_modules/react-native-video/android-exoplayer',
        },
      },
    },
  },
};

もしくはandroid/settings.gradleに以下の記載を追加する必要があります。

include ':react-native-video'
project(':react-native-video').projectDir = new File(rootProject.projectDir, '/../node_modules/react-native-video/android-exoplayer')

How can I force react-native-video to use Exoplayer ? · Issue #2461 · react-native-video/react-native-video

ただ、ExpoのManaged Workflowの場合これらを編集することができない(react-native.config.jsは配置しても意味がない、settings.gradleはそもそもandroidフォルダが無い)ため、ビルド時(Prebuild)にConfig Pluginで更新する必要があります。

Config Pluginの作成

Config Pluginで android/settings.gradle の中身を更新するにはMod PluginのwithSettingsGradleを利用します。

Config Plugins - Expo Documentation

configPlugins/withExoPlayer.js のようなパスにConfigPluginファイルを作成します。

const { withSettingsGradle } = require("@expo/config-plugins")

/**
 * settings.gradleにExoPlayerの設定を追加する
 */
function withExoPlayer(config) {
  return withSettingsGradle(config, config => {
    if (config.modResults.language === "groovy") {
      config.modResults.contents += `
include ':react-native-video'
project(':react-native-video').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-video/android-exoplayer')
`
    } else {
      throw new Error(
        `Cannot setup ExoPlayer because the settings.gradle is not groovy`,
      )
    }
    return config
  })
}

module.exports = withExoPlayer

app.jsonのpluginsの設定に追加します。

{
  "expo": {
    ...,
    "plugins": ["./configPlugins/withExoPlayer"]
  }
}

これでEAS Buildを行うとPrebuild時にConfigPluginが実行されsettings.gradleが更新されます。

最終更新: 2022-09-28 00:45
筆者: @gaishimo 主にReact Nativeでのアプリ開発を行っています。
© 2021 Omoidasu, Inc. All rights reserved.