React Native によるスムーズなビデオ ストリーミング

王林
リリース: 2024-08-24 11:35:02
オリジナル
583 人が閲覧しました

Smooth Video Streaming with React Native

React Native Video を使用してスムーズなビデオ ストリーミング エクスペリエンスを構築する

今日のモバイル中心の世界では、ビデオ ストリーミングは多くのアプリケーションの中核機能です。ビデオ共有プラットフォーム、教育アプリ、マルチメディアが豊富なソーシャル ネットワークのいずれであっても、シームレスなビデオ エクスペリエンスを提供することが不可欠です。クロスプラットフォームのモバイル アプリを構築するための人気のあるフレームワークである React Native では、react-native-video ライブラリを使用してビデオ ストリーミングを簡単に統合できます。

このブログでは、React Native アプリケーションでスムーズなビデオ ストリーミング エクスペリエンスを作成するために、react-native-video をインストール、構成、使用する手順を説明します。


1. インストール

始めるには、React Native プロジェクトに React-native-video ライブラリをインストールする必要があります。

ステップ 1: パッケージをインストールする

まず、npm または Yarn を使用してライブラリをインストールします。

npm install react-native-video react-native-video-cache
ログイン後にコピー

または

yarn add react-native-video react-native-video-cache
ログイン後にコピー

iOS の場合、必要なポッドをインストールする必要がある場合があります:

cd ios
pod install
cd ..
ログイン後にコピー

ステップ 2: iOS/Android 用の追加のネイティブ設定

a) アンドロイド:

i) android/build.gradle

buildscript {
  ext {
    // Enable IMA (Interactive Media Ads) integration with ExoPlayer
    useExoplayerIMA = true

    // Enable support for RTSP (Real-Time Streaming Protocol) with ExoPlayer
    useExoplayerRtsp = true

    // Enable support for Smooth Streaming with ExoPlayer
    useExoplayerSmoothStreaming = true

    // Enable support for DASH (Dynamic Adaptive Streaming over HTTP) with ExoPlayer
    useExoplayerDash = true

    // Enable support for HLS (HTTP Live Streaming) with ExoPlayer
    useExoplayerHls = true
  }
}

allprojects {
    repositories {
        mavenLocal()
        google()
        jcenter()
         maven {
            url "$rootDir/../node_modules/react-native-video-cache/android/libs"
        }
    }
}
ログイン後にコピー

この構成では、ExoPlayer でさまざまなストリーミング プロトコル (IMA、RTSP、Smooth Streaming、DASH、HLS) が有効になり、ローカル、Google、JCenter、react-native-video のカスタム Maven リポジトリを含むリポジトリが設定されます。キャッシュ。
これらの各機能を有効にすると APK のサイズが増加するため、必要な機能のみを有効にしてください。デフォルトで有効になっている機能は次のとおりです: useExoplayerSmoothStreaming、useExoplayerDash、useExoplayerHls

ii) AndroidManifest.xml

    <application
      ...
      android:largeHeap="true" 
      android:hardwareAccelerated="true">
ログイン後にコピー

この組み合わせにより、アプリには大規模なデータセットを処理するのに十分なメモリが確保され (largeHeap 経由)、グラフィックスを効率的にレンダリングできるようになり (hardwareAccelerated 経由)、よりスムーズで安定したユーザー エクスペリエンスが実現します。ただし、どちらもアプリのパフォーマンスとその機能の特定のニーズを考慮して使用する必要があります。

b) iOS:

i) ios/your_app/AppDelegate.mm の DidFinishLaunchingWithOptions 内に次を追加します:

#import <AVFoundation/AVFoundation.h> 

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  self.moduleName = @"your_app";

  // --- You can add your custom initial props in the dictionary below.
  [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
  // --- They will be passed down to the ViewController used by React Native.

  self.initialProps = @{};
  return [super application:application didFinishLaunchingWithOptions:launchOptions];
}
ログイン後にコピー

アプリがバックグラウンドまたはサイレント モードにある場合でも音声が再生され続けるようにする

ii) ios/Podfile:

...
# ENABLE THIS FOR CACHEING THE VIDEOS 
platform :ios, min_ios_version_supported
prepare_react_native_project!
# -- ENABLE THIS FOR CACHEING THE VIDEOS 
$RNVideoUseVideoCaching=true

...

target 'your_app' do

  config = use_native_modules!
  # ENABLE THIS FOR CACHEING THE VIDEOS 
  pod 'SPTPersistentCache', :modular_headers => true;
  pod 'DVAssetLoaderDelegate', :modular_headers => true;

...

ログイン後にコピー

この構成では、キャッシュとアセットの読み込みを処理する特定の CocoaPods (SPTPersistentCache および DVAssetLoaderDelegate) を追加することで、iOS プロジェクトでのビデオ キャッシュを有効にします。 $RNVideoUseVideoCaching=true フラグは、プロジェクトがこれらのキャッシュ機能を使用する必要があることを示します。この設定により、ビデオ ファイルを再フェッチする必要性が減り、ビデオ再生のパフォーマンスが向上します。


2. 使用方法:

import Video from 'react-native-video';
import convertToProxyURL from 'react-native-video-cache';

          <Video
  // Display a thumbnail image while the video is loading
  poster={item.thumbUri}

  // Specifies how the thumbnail should be resized to cover the entire video area
  posterResizeMode="cover"

  // Sets the video source URI if the video is visible; otherwise, it avoids loading the video
  source={
    isVisible
      ? { uri: convertToProxyURL(item.videoUri) } // Converts the video URL to a proxy URL if visible
      : undefined // Avoid loading the video if not visible
  }

  // Configures buffer settings to manage video loading and playback
  bufferConfig={{
    minBufferMs: 2500, // Minimum buffer before playback starts
    maxBufferMs: 3000, // Maximum buffer allowed
    bufferForPlaybackMs: 2500, // Buffer required to start playback
    bufferForPlaybackAfterRebufferMs: 2500, // Buffer required after rebuffering
  }}

  // Ignores the silent switch on the device, allowing the video to play with sound even if the device is on silent mode
  ignoreSilentSwitch={'ignore'}

  // Prevents the video from playing when the app is inactive or in the background
  playWhenInactive={false}
  playInBackground={false}

  // Disables the use of TextureView, which can optimize performance but might limit certain effects
  useTextureView={false}

  // Hides the default media controls provided by the video player
  controls={false}

  // Disables focus on the video, which is useful for accessibility and UI focus management
  disableFocus={true}

  // Applies the defined styles to the video container
  style={styles.videoContainer}

  // Pauses the video based on the isPaused state
  paused={isPaused}

  // Repeats the video playback indefinitely
  repeat={true}

  // Hides the shutter view (a black screen that appears when the video is loading or paused)
  hideShutterView

  // Sets the minimum number of retry attempts when the video fails to load
  minLoadRetryCount={5}

  // Ensures the video maintains the correct aspect ratio by covering the entire view area
  resizeMode="cover"

  // Sets the shutter color to transparent, so the shutter view is invisible
  shutterColor="transparent"

  // Callback function that is triggered when the video is ready for display
  onReadyForDisplay={handleVideoLoad}
/>

ログイン後にコピー

3. 最適化のヒント

ビデオをスムーズに再生するには:

  • CDN を使用する: 読み込みを高速化するために、CDN (コンテンツ配信ネットワーク) でビデオをホストします。
  • アダプティブ ストリーミング: アダプティブ ストリーミング (HLS または DASH) を実装して、ネットワークの状況に基づいてビデオ品質を調整します。
  • ビデオのプリロード: 再生中のバッファリングを避けるためにビデオをプリロードします。
  • ビデオ ファイルの最適化: 品質を落とさずにビデオ ファイルを圧縮し、読み込み時間を短縮します。

結論

react-native-video ライブラリは、React Native アプリケーションにビデオ機能を追加するための強力なツールです。広範な構成オプションとイベント処理機能により、ユーザー向けにスムーズでカスタマイズされたビデオ ストリーミング エクスペリエンスを作成できます。基本的なプレーヤーが必要な場合でも、完全にカスタマイズされたプレーヤーが必要な場合でも、react-native-video が対応します。

以上がReact Native によるスムーズなビデオ ストリーミングの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ソース:dev.to
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
著者別の最新記事
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!