react-native-youtube

repository·master·Indexed 22 days ago

https://github.com/davidohayon669/react-native-youtube

A React Native component for playing YouTube videos using WKWebView on iOS and the YouTube Android Player API on Android. Version 2.0.2 provides a declarative <YouTube /> component to control playback, fullscreen mode, and looping, as well as standalone player classes for both platforms.

Tokens
2.7K
Snippets
8
Records
14
Agent score
28%

What's inside react-native-youtube

  1. Manage multiple YouTube instances on Android

    master

    The YouTube API for Android operates as a singleton. This means only one player can be active at a time.

    Behavioral Notes:

    • If two players are mounted (e.g., during a screen transition), the new player will take focus.
    • Once the new player is unmounted, the previous player cannot regain control of the singleton.
    • Requirement: You must re-mount the original <YouTube /> component if you need to return to it after a new player has been mounted.
  2. Test local changes in the Example App

    master

    If you are developing the library and want to test your changes in the /example app, you must re-install the package from the root directory after making changes. This command packs the root directory into an npm package .tar file and installs it locally into the example app.

    Run this from the root of the repository:

    npm run install-root
  3. Enable audio playback in iOS background/vibrate mode

    master

    To ensure sound is activated even when an iPhone is in vibrate mode, modify your AppDelegate.m file:

    1. Add #import <AVFoundation/AVFoundation.h>
    2. Add [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error: nil]; inside your didFinishLaunchingWithOptions method.
    // In AppDelegate.m
    #import <AVFoundation/AVFoundation.h>
    
    // Inside didFinishLaunchingWithOptions
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error: nil];
  4. Install react-native-youtube

    master

    Install the library using npm. React Native handles native module linking automatically.

    Android: Linking is supported via Gradle and is automatic after installation. Note: The official YouTube app must be installed on the device, otherwise an error with SERVICE_MISSING or SERVICE_DISABLED will be triggered.

    iOS: Linking is handled by Cocoapods. Run pod install in your ios directory after installation.

    $ npm install react-native-youtube -S
  5. Set up the Example App for development

    master

    To run the included example project to test functionalities, follow these steps:

    1. Clone the repository and navigate to the example directory:
      git clone https://github.com/davidohayon669/react-native-youtube.git
      cd react-native-youtube/example
      npm install
    2. For iOS, install CocoaPods:
      cd ios
      pod install
    3. Build and run using react-native run-ios or react-native run-android.
    $ git clone https://github.com/davidohayon669/react-native-youtube.git
    $ cd react-native-youtube/example
    $ npm install
    $ cd ios
    $ pod install
  6. Troubleshoot Android YouTube Player limitations

    master

    The Android implementation uses the official YouTube Android Player API, which imposes certain restrictions that may cause errors:

    • UNAUTHORIZED_OVERLAY: You cannot cover the player view with other UI elements. Some React Native components (like certain navigation libraries) might trigger this error by attempting to overlay the player.
    • PLAYER_VIEW_TOO_SMALL: The player cannot be rendered at an excessively small size.

    If you encounter these errors, ensure your layout does not attempt to overlay or shrink the player view beyond the API's limits.

  7. Handle video changes on Android

    master

    Due to bugs in the underlying Android YouTube API, changing the videoId, videoIds, or playlistId props while the <YouTube /> component is already mounted can cause issues. Additionally, looping through a playlist or videoIds is currently broken on Android.

    Recommended Workaround: Instead of updating props on an existing component, unmount the current <YouTube /> instance and mount a new one whenever you need to replace the video or playlist.

  8. Use the YouTube component

    master

    The <YouTube /> component allows you to embed a YouTube player declaratively in your React Native application. You can control playback, fullscreen mode, looping, and handle various player events.

    import YouTube from 'react-native-youtube';
    
    <YouTube
      videoId="KVZ-P-ZI6W4" // The YouTube video ID
      play // control playback of video with true/false
      fullscreen // control whether the video should play in fullscreen or inline
      loop // control whether the video should loop when ended
      onReady={e => this.setState({ isReady: true })}
      onChangeState={e => this.setState({ status: e.state })}
      onChangeQuality={e => this.setState({ quality: e.quality })}
      onError={e => this.setState({ error: e.error })}
      style={{ alignSelf: 'stretch', height: 300 }}
    />
  9. Use YouTubeStandaloneAndroid

    master

    The YouTubeStandaloneAndroid class provides static methods to launch standalone players on Android. All methods require an apiKey.

    playVideo(options)

    Launches a standalone player for a single video.

    • apiKey (string): Required.
    • videoId (string): Required.
    • autoplay (boolean): Default false.
    • lightboxMode (boolean): Play in lightbox instead of fullscreen. Default false.
    • startTime (number): Starting time in seconds. Default 0.

    playVideos(options)

    Launches a standalone player for a list of videos.

    • apiKey (string): Required.
    • videoIds (string[]): Required.
    • autoplay (boolean): Default false.
    • lightboxMode (boolean): Default false.
    • startIndex (number): Index of first video. Default 0.
    • startTime (number): Starting time in seconds. Default 0.

    playPlaylist(options)

    Launches a standalone player for a YouTube playlist.

    • apiKey (string): Required.
    • playlistId (string): Required.
    • autoplay (boolean): Default false.
    • lightboxMode (boolean): Default false.
    • startIndex (number): Index of first video. Default 0.
    • startTime (number): Starting time in seconds. Default 0.
    import { YouTubeStandaloneAndroid } from 'react-native-youtube';
    
    YouTubeStandaloneAndroid.playVideo({
      apiKey: 'YOUR_API_KEY',
      videoId: 'KVZ-P-ZI6W4',
      autoplay: true,
      startTime: 120,
    })
      .then(() => console.log('Standalone Player Exited'))
      .catch(errorMessage => console.error(errorMessage));
  10. YouTube Component Events

    master

    The <YouTube /> component emits the following events:

    • onReady: Called once when the player is set up.
    • onChangeState: Emits e.state. Common values: buffering, playing, paused. (Android also includes seeking with e.currentTime).
    • onChangeQuality: Emits e.quality.
    • onError: Emits e.error.
    • onChangeFullscreen: Emits e.isFullscreen (boolean).
    • onProgress (iOS only): Called every 500ms with e.currentTime (seconds).
  11. YouTube Component Properties

    master

    The <YouTube /> component accepts the following props:

    PropTypePlatformDescription
    apiKeystringAndroidRequired. Your YouTube developer API Key.
    videoIdstringAllThe YouTube video ID to play.
    videoIdsstring[]AllArray of IDs for an interactive playlist. Overridden by videoId at start.
    playlistIdstringAllYouTube Playlist ID. Overridden by videoId and videoIds at start.
    playbooleanAllControls playback (true/false). Default: false.
    loopbooleanAllLoops the video. Default: false.
    fullscreenbooleanAllPlays in fullscreen or inline. Default: false.
    controlsnumberAllPlayer control scheme. 0, 1, or 2. Default: 1. Android: 0=CHROMELESS, 1=DEFAULT, 2=MINIMAL.
    showFullscreenButtonbooleanAllShow/hide fullscreen button. Default: true.
    showinfobooleaniOSHide video title/uploader before playback. Default: true.
    modestbrandingbooleaniOSHide YouTube logo. Default: false.
    originstringiOSSecurity measure for iFrame API.
    relbooleaniOSShow related videos at end. Default: true.
    resumePlayAndroidbooleanAndroidResume playback after app resumes from background. Default: true.