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용 추가 기본 설정

가) 안드로이드:

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을 통해)를 처리할 수 있는 충분한 메모리를 확보하고 그래픽을 효율적으로 렌더링(하드웨어 가속을 통해)할 수 있어 더욱 부드럽고 안정적인 사용자 환경을 제공할 수 있습니다. 그러나 둘 다 앱의 성능과 기능의 특정 요구 사항을 고려하여 사용해야 합니다.

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;

...

로그인 후 복사

이 구성을 사용하면 캐싱 및 자산 로드를 처리하는 특정 CocoaPod(SPTPertantCache 및 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(Content Delivery Network)에 동영상을 호스팅하세요.
  • 적응형 스트리밍: 적응형 스트리밍(HLS 또는 DASH)을 구현하여 네트워크 상태에 따라 비디오 품질을 조정합니다.
  • 동영상 미리 로드: 재생 중 버퍼링을 방지하려면 동영상을 미리 로드하세요.
  • 비디오 파일 최적화: 품질 저하 없이 비디오 파일을 압축하여 로드 시간을 줄입니다.

결론

react-native-video 라이브러리는 React Native 애플리케이션에 비디오 기능을 추가하기 위한 강력한 도구입니다. 광범위한 구성 옵션과 이벤트 처리 기능을 통해 사용자를 위한 원활하고 맞춤화된 비디오 스트리밍 환경을 만들 수 있습니다. 기본 플레이어가 필요하든 완전히 맞춤화된 플레이어가 필요하든, React-Native-Video가 해결해 드립니다.

위 내용은 React Native를 사용한 원활한 비디오 스트리밍의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
저자별 최신 기사
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!