### Start Local Development Server
Source: https://github.com/lonelycpp/react-native-youtube-iframe/blob/master/website/README.md
Starts a local development server for the website. Changes are reflected live without requiring a server restart, facilitating rapid development.
```shell
yarn start
```
--------------------------------
### Install Project Dependencies
Source: https://github.com/lonelycpp/react-native-youtube-iframe/blob/master/website/README.md
Installs the necessary dependencies for the project using Yarn. This is typically the first step before running other commands.
```shell
yarn
```
--------------------------------
### Playlist Prop Example - react-native-youtube-iframe
Source: https://github.com/lonelycpp/react-native-youtube-iframe/blob/master/docs/props.mdx
Demonstrates how to use the 'playList' prop to specify a YouTube playlist. It accepts either a playlist ID string or an array of video ID strings.
```javascript
playList={'PLbpi6ZahtOH6Blw3RGYpWkSByi_T7Rygb'}
or
playList={['QRt7LjqJ45k', 'fHsa9DqmId8']}
```
--------------------------------
### Add Local Dependency to package.json
Source: https://github.com/lonelycpp/react-native-youtube-iframe/blob/master/CONTRIBUTING.md
This snippet shows how to add the react-native-youtube-iframe library as a local dependency in your test application's package.json file. This allows you to test changes made directly in the cloned repository without publishing them. Ensure the path points to your cloned folder.
```json
{
"dependencies": {
"react-native-youtube-iframe": "path/to/cloned/folder"
}
}
```
--------------------------------
### React Native YouTube Iframe Component Example
Source: https://context7.com/lonelycpp/react-native-youtube-iframe/llms.txt
Demonstrates the usage of the YoutubeIframe component for embedding and controlling YouTube videos within a React Native application. It includes state management for playback, event handlers for player state changes and errors, and imperative API calls for seeking and retrieving current playback time. Dependencies include React, React Native core components, and the react-native-youtube-iframe library.
```jsx
import React, { useRef, useState } from 'react';
import { View, Button, StyleSheet } from 'react-native';
import YoutubeIframe, { PLAYER_STATES } from 'react-native-youtube-iframe';
const VideoPlayer = () => {
const playerRef = useRef(null);
const [playing, setPlaying] = useState(false);
const [currentTime, setCurrentTime] = useState(0);
const onStateChange = (state) => {
console.log('Player state:', state);
if (state === PLAYER_STATES.PLAYING) {
setPlaying(true);
} else if (state === PLAYER_STATES.PAUSED) {
setPlaying(false);
}
};
const onError = (error) => {
console.error('Player error:', error);
};
const onReady = () => {
console.log('Player is ready');
};
const handleGetCurrentTime = async () => {
if (playerRef.current) {
const time = await playerRef.current.getCurrentTime();
setCurrentTime(time);
console.log('Current time:', time);
}
};
const handleSeek = () => {
if (playerRef.current) {
playerRef.current.seekTo(30, true);
}
};
return (
);
};
const styles = StyleSheet.create({
container: { flex: 1, padding: 20 },
videoContainer: { marginBottom: 20 },
webview: { opacity: 0.99 },
controls: { flexDirection: 'row', justifyContent: 'space-around' },
});
export default VideoPlayer;
```
--------------------------------
### Configure React Native YouTube Iframe with Advanced Props
Source: https://context7.com/lonelycpp/react-native-youtube-iframe/llms.txt
This snippet demonstrates how to configure the react-native-youtube-iframe component with advanced props. It allows customization of video playback, player controls, captions, loop behavior, and more, by passing an `initialPlayerParams` object and other relevant props. The example also includes basic playback controls.
```jsx
import React, { useState } from 'react';
import { View, Button, StyleSheet } from 'react-native';
import YoutubeIframe from 'react-native-youtube-iframe';
const AdvancedPlayer = () => {
const [playing, setPlaying] = useState(false);
const [volume, setVolume] = useState(75);
const [playbackRate, setPlaybackRate] = useState(1);
return (
console.log('Advanced player ready')}
/>
setPlaying(!playing)}
/>
setVolume(50)}
/>
setPlaybackRate(1.5)}
/>
setPlaybackRate(1)}
/>
);
};
const styles = StyleSheet.create({
container: { flex: 1, padding: 20, backgroundColor: '#fff' },
videoContainer: { borderRadius: 10, overflow: 'hidden', marginBottom: 20 },
webview: { opacity: 0.99, backgroundColor: 'black' },
controls: {
flexDirection: 'row',
justifyContent: 'space-around',
flexWrap: 'wrap',
gap: 10,
},
});
export default AdvancedPlayer;
```
--------------------------------
### Play YouTube Playlists with react-native-youtube-iframe
Source: https://context7.com/lonelycpp/react-native-youtube-iframe/llms.txt
This snippet demonstrates how to play YouTube playlists using either a playlist ID or an array of video IDs. It allows for custom start index and controls playback state. Dependencies include React, useState, View, Button, StyleSheet, and YoutubeIframe.
```jsx
import React, { useState } from 'react';
import { View, Button, StyleSheet } from 'react-native';
import YoutubeIframe from 'react-native-youtube-iframe';
const PlaylistPlayer = () => {
const [playing, setPlaying] = useState(false);
const [useArrayPlaylist, setUseArrayPlaylist] = useState(false);
// Playlist as array of video IDs
const videoPlaylist = ['dQw4w9WgXcQ', 'kJQP7kiw5Fk', 'fJ9rUzIMcZQ'];
// Playlist as YouTube playlist ID
const playlistId = 'PLbpi6ZahtOH6Blw3RGYpWkSByi_T7Rygb';
return (
console.log('Playlist ready')}
onChangeState={(state) => console.log('State:', state)}
/>
setPlaying(!playing)}
/>
setUseArrayPlaylist(!useArrayPlaylist)}
/>
);
};
const styles = StyleSheet.create({
container: { flex: 1, padding: 20 },
controls: { flexDirection: 'row', justifyContent: 'space-around', marginTop: 20 },
});
export default PlaylistPlayer;
```
--------------------------------
### Get Current Playback Time - JavaScript
Source: https://github.com/lonelycpp/react-native-youtube-iframe/blob/master/docs/ref_methods.mdx
The `getCurrentTime` function returns a Promise that resolves to the elapsed time in seconds since the video started playing. This is useful for tracking progress or implementing custom playback controls.
```javascript
playerRef.current?.getCurrentTime().then(
currentTime => console.log({currentTime})
);
```
--------------------------------
### Get Video Duration - JavaScript
Source: https://github.com/lonelycpp/react-native-youtube-iframe/blob/master/docs/ref_methods.mdx
The `getDuration` function returns a Promise that resolves to the total duration of the YouTube video in seconds. For live streams, it returns the elapsed time since the stream began. It's important to note that `getDuration()` returns 0 until the video's metadata is loaded, typically right after playback starts.
```javascript
playerRef.current?.getDuration().then(
getDuration => console.log({getDuration})
);
```
--------------------------------
### Log Player Details using useRef - JavaScript
Source: https://github.com/lonelycpp/react-native-youtube-iframe/blob/master/docs/ref_methods.mdx
This snippet demonstrates how to use the `useRef` hook to get a reference to the YoutubePlayer component. It shows how to call asynchronous functions like `getCurrentTime` and `getDuration` on the player's current instance, logging the results to the console. This pattern is essential for interacting with player methods in React Native.
```javascript
import React, {useRef} from 'react';
import YoutubePlayer, {YoutubeIframeRef} from "react-native-youtube-iframe";
const App = () => {
const playerRef = useRef();
// typescript
// const playerRef = useRef(null);
return (
{
playerRef.current?.getCurrentTime().then(
currentTime => console.log({currentTime})
);
playerRef.current?.getDuration().then(
getDuration => console.log({getDuration})
);
}}
/>
);
};
```
--------------------------------
### Get Current Playback Rate - JavaScript
Source: https://github.com/lonelycpp/react-native-youtube-iframe/blob/master/docs/ref_methods.mdx
The `getPlaybackRate` function returns a Promise that resolves to a number indicating the current playback speed of the video. The default rate is 1 (normal speed), but values like 0.25, 0.5, 1.5, and 2 are also possible.
```javascript
playerRef.current?.getPlaybackRate().then(playbackRate => console.log({playbackRate}));
```
--------------------------------
### Get Current Volume Level - JavaScript
Source: https://github.com/lonelycpp/react-native-youtube-iframe/blob/master/docs/ref_methods.mdx
The `getVolume` function returns a Promise that resolves to a number representing the player's current volume, an integer between 0 and 100. Importantly, this function returns the volume level even if the player is muted.
```javascript
playerRef.current?.getVolume().then(volume => console.log({volume}));
```
--------------------------------
### Get Available Playback Rates - JavaScript
Source: https://github.com/lonelycpp/react-native-youtube-iframe/blob/master/docs/ref_methods.mdx
The `getAvailablePlaybackRates` function returns a Promise that resolves to an array of numbers representing all supported playback speeds for the video. The array is ordered from slowest to fastest. Even if variable playback speeds are not supported, the array will always contain at least the value 1.
```javascript
playerRef.current?.getAvailablePlaybackRates().then(availablePlaybackRates => console.log({availablePlaybackRates}));
```
--------------------------------
### React Navigation: Use Horizontal Transition Animation
Source: https://github.com/lonelycpp/react-native-youtube-iframe/blob/master/docs/navigation-crash.mdx
This solution involves configuring react-navigation's Stack Navigator to use a transition animation that only involves translations. This can prevent crashes when navigating between screens containing webviews and the YouTubePlayer component. Ensure you have 'react-navigation' installed.
```jsx
```
--------------------------------
### Display Elapsed Video Time with setInterval in React Native
Source: https://github.com/lonelycpp/react-native-youtube-iframe/blob/master/docs/show-elapsed-time.mdx
This JavaScript code snippet demonstrates how to continuously fetch the current playback time of a YouTube video using the `getCurrentTime` method from `react-native-youtube-iframe`. The fetched time is then formatted and updated every 100 milliseconds using `setInterval`. It relies on React's `useState`, `useRef`, and `useEffect` hooks for state management and side effects. Ensure `react-native-youtube-iframe` is installed and imported.
```javascript
import React, {useState, useRef, useEffect} from 'react';
import {Text, View} from 'react-native';
import YoutubePlayer from 'react-native-youtube-iframe';
const App = () => {
const [elapsed, setElapsed] = useState(0);
const playerRef = useRef();
useEffect(() => {
const interval = setInterval(async () => {
const elapsed_sec = await playerRef.current.getCurrentTime(); // this is a promise. dont forget to await
// calculations
const elapsed_ms = Math.floor(elapsed_sec * 1000);
const ms = elapsed_ms % 1000;
const min = Math.floor(elapsed_ms / 60000);
const seconds = Math.floor((elapsed_ms - min * 60000) / 1000);
setElapsed(
min.toString().padStart(2, '0') +
':' +
seconds.toString().padStart(2, '0') +
':' +
ms.toString().padStart(3, '0'),
);
}, 100); // 100 ms refresh. increase it if you don't require millisecond precision
return () => {
clearInterval(interval);
};
}, []);
return (
<>
{'elapsed time'}{elapsed}
>
);
};
```
--------------------------------
### Deploy Website to GitHub Pages
Source: https://github.com/lonelycpp/react-native-youtube-iframe/blob/master/website/README.md
Builds the website and deploys it to the `gh-pages` branch, specifically for hosting on GitHub Pages. It allows configuration of the Git user and SSH usage.
```shell
GIT_USER=lonelycpp CURRENT_BRANCH= USE_SSH=true yarn deploy
```
--------------------------------
### Build Static Website Content
Source: https://github.com/lonelycpp/react-native-youtube-iframe/blob/master/website/README.md
Generates the static content for the website into the `build` directory. This output can be hosted on any static content hosting service.
```shell
yarn build
```
--------------------------------
### Initialize YouTube Iframe Player and Handle Events (JavaScript)
Source: https://github.com/lonelycpp/react-native-youtube-iframe/blob/master/website/static/iframe_v2.html
This snippet initializes the YouTube Iframe Player API, creates a player instance with configurable options, and sets up event listeners for various player states. It sends messages back to the React Native application upon player events.
```javascript
const randomPlayerId="player"+Date.now();document.getElementById("player").id=randomPlayerId;const parsedUrl=new URL(window.location.href),UrlQueryData=parsedUrl.searchParams.get("data"),{end:end,list:list,color:color,start:start,rel_s:rel_s,loop_s:loop_s,listType:listType,playerLang:playerLang,playlist:playlist,videoId_s:videoId_s,controls_s:controls_s,cc_lang_pref_s:cc_lang_pref_s,contentScale_s:contentScale_s,allowWebViewZoom:allowWebViewZoom,modestbranding_s:modestbranding_s,iv_load_policy:iv_load_policy,preventFullScreen_s:preventFullScreen_s,showClosedCaptions_s:showClosedCaptions_s}=JSON.parse(UrlQueryData);function sendMessageToRN(e){window.ReactNativeWebView.postMessage(JSON.stringify(e))}let metaString="";contentScale_s&&(metaString+=`initial-scale=${contentScale_s}, `),allowWebViewZoom||(metaString+=`maximum-scale=${contentScale_s}`);const viewport=document.querySelector("meta[name=viewport]");viewport.setAttribute("content","width=device-width, "+metaString);var tag=document.createElement("script");tag.src="https://www.youtube.com/iframe_api";var player,firstScriptTag=document.getElementsByTagName("script")[0];function onYouTubeIframeAPIReady(){player=new YT.Player(randomPlayerId,{width:"1000",height:"1000",videoId:videoId_s,playerVars:{end:end,rel:rel_s,list:list,color:color,loop:loop_s,start:start,playsinline:1,hl:playerLang,playlist:playlist,listType:listType,controls:controls_s,fs:preventFullScreen_s,cc_lang_pref:cc_lang_pref_s,iv_load_policy:iv_load_policy,modestbranding:modestbranding_s,cc_load_policy:showClosedCaptions_s},events:{onReady:onPlayerReady,onError:onPlayerError,onStateChange:onPlayerStateChange,onPlaybackRateChange:onPlaybackRateChange,onPlaybackQualityChange:onPlaybackQualityChange}})}function onPlayerError(e){sendMessageToRN({eventType:"playerError",data:e.data})}function onPlaybackRateChange(e){sendMessageToRN({eventType:"playbackRateChange",data:e.data})}function onPlaybackQualityChange(e){sendMessageToRN({eventType:"playerQualityChange",data:e.data})}function onPlayerReady(e){sendMessageToRN({eventType:"playerReady"})}function onPlayerStateChange(e){sendMessageToRN({eventType:"playerStateChange",data:e.data})}firstScriptTag.parentNode.insertBefore(tag,firstScriptTag);
```
--------------------------------
### Access Player Info Imperatively with react-native-youtube-iframe Ref
Source: https://context7.com/lonelycpp/react-native-youtube-iframe/llms.txt
This snippet shows how to access player information and control the YouTube player imperatively using ref methods. These methods return promises, allowing you to retrieve data like duration, current time, video URL, volume, and playback status. Dependencies include React, useRef, useState, View, Button, Text, StyleSheet, and YoutubeIframe.
```jsx
import React, { useRef, useState } from 'react';
import { View, Button, Text, StyleSheet } from 'react-native';
import YoutubeIframe from 'react-native-youtube-iframe';
const PlayerInfo = () => {
const playerRef = useRef(null);
const [info, setInfo] = useState({
duration: 0,
currentTime: 0,
videoUrl: '',
volume: 0,
isMuted: false,
playbackRate: 1,
availableRates: [],
});
const getAllInfo = async () => {
if (playerRef.current) {
try {
const [duration, currentTime, videoUrl, volume, isMuted, playbackRate, availableRates] =
await Promise.all([
playerRef.current.getDuration(),
playerRef.current.getCurrentTime(),
playerRef.current.getVideoUrl(),
playerRef.current.getVolume(),
playerRef.current.isMuted(),
playerRef.current.getPlaybackRate(),
playerRef.current.getAvailablePlaybackRates(),
]);
setInfo({
duration,
currentTime,
videoUrl,
volume,
isMuted,
playbackRate,
availableRates,
});
} catch (error) {
console.error('Error getting player info:', error);
}
}
};
return (
console.log('Ready to get info')}
/>
Duration: {info.duration.toFixed(2)}sCurrent Time: {info.currentTime.toFixed(2)}sVideo URL: {info.videoUrl}Volume: {info.volume}Is Muted: {info.isMuted.toString()}Playback Rate: {info.playbackRate}Available Rates: {info.availableRates.join(', ')}
);
};
const styles = StyleSheet.create({
container: { flex: 1, padding: 20 },
infoContainer: { marginTop: 20, padding: 10, backgroundColor: '#f0f0f0' },
});
export default PlayerInfo;
```
--------------------------------
### Initialize YouTube Player and Handle Events (JavaScript)
Source: https://github.com/lonelycpp/react-native-youtube-iframe/blob/master/iframe.html
This snippet initializes the YouTube Iframe Player API and sets up event listeners for various player states. It parses video details from the URL and sends messages to React Native upon significant player events. Dependencies include the YouTube Iframe API script.
```javascript
const randomPlayerId = 'player' + Date.now();
document.getElementById('player').id = randomPlayerId;
const parsedUrl = new URL(window.location.href);
const UrlQueryData = parsedUrl.searchParams.get('data');
const { end, list, color, start, rel_s, loop_s, listType, playerLang, playlist, videoId_s, controls_s, cc_lang_pref_s, contentScale_s, allowWebViewZoom, modestbranding_s, iv_load_policy, preventFullScreen_s, showClosedCaptions_s, } = JSON.parse(UrlQueryData);
function sendMessageToRN(msg) {
window.ReactNativeWebView.postMessage(JSON.stringify(msg));
}
let metaString = '';
if (contentScale_s) {
metaString += `initial-scale=${contentScale_s}, `;
}
if (!allowWebViewZoom) {
metaString += `maximum-scale=${contentScale_s}`;
}
const viewport = document.querySelector('meta[name=viewport]');
vport.setAttribute('content', 'width=device-width, ' + metaString);
var tag = document.createElement('script');
tag.src = 'https://www.youtube.com/iframe_api';
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player(randomPlayerId, {
width: '1000',
height: '1000',
videoId: videoId_s,
playerVars: {
end: end,
rel: rel_s,
list: list,
color: color,
loop: loop_s,
start: start,
playsinline: 1,
hl: playerLang,
playlist: playlist,
listType: listType,
controls: controls_s,
fs: preventFullScreen_s,
cc_lang_pref: cc_lang_pref_s,
iv_load_policy: iv_load_policy,
modestbranding: modestbranding_s,
cc_load_policy: showClosedCaptions_s,
},
events: {
onReady: onPlayerReady,
onError: onPlayerError,
onStateChange: onPlayerStateChange,
onPlaybackRateChange: onPlaybackRateChange,
onPlaybackQualityChange: onPlaybackQualityChange,
},
});
}
function onPlayerError(event) {
sendMessageToRN({eventType: 'playerError', data: event.data});
}
function onPlaybackRateChange(event) {
sendMessageToRN({eventType: 'playbackRateChange', data: event.data});
}
function onPlaybackQualityChange(event) {
sendMessageToRN({eventType: 'playerQualityChange', data: event.data});
}
function onPlayerReady(event) {
sendMessageToRN({eventType: 'playerReady'});
}
function onPlayerStateChange(event) {
sendMessageToRN({eventType: 'playerStateChange', data: event.data});
}
```
--------------------------------
### Fetch YouTube Video Metadata using oEmbed API (JavaScript)
Source: https://context7.com/lonelycpp/react-native-youtube-iframe/llms.txt
Fetches metadata for a YouTube video using the YouTube oEmbed API. This function does not require YouTube Data API keys. It takes a video ID as input and returns an object containing video details such as title, author, thumbnail, and embed HTML. Error handling is included for network or API issues.
```javascript
import { getYoutubeMeta } from 'react-native-youtube-iframe';
const fetchVideoMetadata = async () => {
try {
const videoId = 'dQw4w9WgXcQ';
const metadata = await getYoutubeMeta(videoId);
console.log('Video Title:', metadata.title);
console.log('Author:', metadata.author_name);
console.log('Author URL:', metadata.author_url);
console.log('Thumbnail URL:', metadata.thumbnail_url);
console.log('Thumbnail Size:', `${metadata.thumbnail_width}x${metadata.thumbnail_height}`);
console.log('Provider:', metadata.provider_name);
console.log('Provider URL:', metadata.provider_url);
console.log('Embed HTML:', metadata.html);
console.log('Video Type:', metadata.type);
console.log('oEmbed Version:', metadata.version);
return metadata;
} catch (error) {
console.error('Error fetching metadata:', error);
throw error;
}
};
```
--------------------------------
### Initialize YouTube Iframe Player and Handle Events (JavaScript)
Source: https://github.com/lonelycpp/react-native-youtube-iframe/blob/master/website/static/iframe.html
This snippet initializes the YouTube Iframe Player and sets up event listeners for various player states and errors. It communicates back to the React Native application by sending JSON messages through `window.ReactNativeWebView.postMessage`. The player configuration, including video ID and playback options, is parsed from the URL query parameters.
```javascript
const randomPlayerId="player"+Date.now();document.getElementById("player").id=randomPlayerId;const parsedUrl=new URL(window.location.href),UrlQueryData=parsedUrl.searchParams.get("data"),{end:end,list:list,color:color,start:start,rel_s:rel_s,loop_s:loop_s,listType:listType,playerLang:playerLang,playlist:playlist,videoId_s:videoId_s,controls_s:controls_s,cc_lang_pref_s:cc_lang_pref_s,contentScale_s:contentScale_s,allowWebViewZoom:allowWebViewZoom,modestbranding_s:modestbranding_s,iv_load_policy:iv_load_policy,preventFullScreen_s:preventFullScreen_s,showClosedCaptions_s:showClosedCaptions_s}=JSON.parse(UrlQueryData);function sendMessageToRN(e){window.ReactNativeWebView.postMessage(JSON.stringify(e))}let metaString="";contentScale_s&&(metaString+=`initial-scale=${contentScale_s}, `),allowWebViewZoom||(metaString+=`maximum-scale=${contentScale_s}`);const viewport=document.querySelector("meta[name=viewport]");viewport.setAttribute("content","width=device-width, "+metaString);var tag=document.createElement("script");tag.src="https://www.youtube.com/iframe_api";var player,firstScriptTag=document.getElementsByTagName("script")[0];function onYouTubeIframeAPIReady(){player=new YT.Player(randomPlayerId,{width:"1000",height:"1000",videoId:videoId_s,playerVars:{end:end,rel:rel_s,list:list,color:color,loop:loop_s,start:start,playsinline:1,hl:playerLang,playlist:playlist,listType:listType,controls:controls_s,fs:preventFullScreen_s,cc_lang_pref:cc_lang_pref_s,iv_load_policy:iv_load_policy,modestbranding:modestbranding_s,cc_load_policy:showClosedCaptions_s},events:{onReady:onPlayerReady,onError:onPlayerError,onStateChange:onPlayerStateChange,onPlaybackRateChange:onPlaybackRateChange,onPlaybackQualityChange:onPlaybackQualityChange}})}function onPlayerError(e){sendMessageToRN({eventType:"playerError",data:e.data})}function onPlaybackRateChange(e){sendMessageToRN({eventType:"playbackRateChange",data:e.data})}function onPlaybackQualityChange(e){sendMessageToRN({eventType:"playerQualityChange",data:e.data})}function onPlayerReady(e){sendMessageToRN({eventType:"playerReady"})}function onPlayerStateChange(e){sendMessageToRN({eventType:"playerStateChange",data:e.data})}firstScriptTag.parentNode.insertBefore(tag,firstScriptTag);var isFullScreen=!1;function onFullScreenChange(){isFullScreen=document.fullscreenElement||document.msFullscreenElement||document.mozFullScreenElement||document.webkitFullscreenElement,sendMessageToRN({eventType:"fullScreenChange",data:Boolean(isFullScreen)})}document.addEventListener("fullscreenchange",onFullScreenChange),document.addEventListener("msfullscreenchange",onFullScreenChange),document.addEventListener("mozfullscreenchange",onFullScreenChange),document.addEventListener("webkitfullscreenchange",onFullScreenChange)
```
--------------------------------
### Player Properties and Methods
Source: https://github.com/lonelycpp/react-native-youtube-iframe/blob/master/docs/props.mdx
This section details properties that control player behavior like mute and volume, and methods related to playback rate, along with their associated events.
```APIDOC
## Player Properties and Methods
### `mute`
Flag to tell the player to mute the video.
- **Type**: `Boolean`
### `volume`
Sets the volume. Accepts an integer between `0` and `100`.
- **Type**: `Number`
### `playbackRate`
This sets the suggested playback rate for the current video. If the playback rate changes, it will only change for the video that is already cued or being played.
- **Type**: `Number`
- **Behavior**: Calling this function does not guarantee that the playback rate will actually change. However, if the playback rate does change, the `onPlaybackRateChange` event will fire. The player will round unsupported values down to the nearest supported value towards 1.
### `onPlaybackRateChange`
This event fires whenever the video playback rate changes. Your application should respond to the event and should not assume that the playback rate will automatically change when the `playbackRate` value changes.
- **Type**: `function(playbackRate: Number)`
- **Note**: The `getAvailablePlaybackRates` method returns a list of the valid playback rates for the video currently cued or playing.
```
--------------------------------
### Fetch YouTube Video Metadata with getYoutubeMeta
Source: https://github.com/lonelycpp/react-native-youtube-iframe/blob/master/docs/module_methods.mdx
The `getYoutubeMeta` function fetches metadata for a given YouTube video ID using the oEmbed specification. It returns a promise that resolves with an object containing various video details such as title, author, URL, thumbnail, and embeddable HTML. This method is useful for displaying video information before or during playback.
```javascript
import {Alert} from 'react-native';
import {getYoutubeMeta} from 'react-native-youtube-iframe';
getYoutubeMeta('sNhhvQGsMEc').then(meta => {
Alert.alert('title of the video : ' + meta.title);
});
```
--------------------------------
### WebView: Enable Hardware Texture Rendering
Source: https://github.com/lonelycpp/react-native-youtube-iframe/blob/master/docs/navigation-crash.mdx
Setting the `renderToHardwareTextureAndroid` prop to `true` for the webview can improve performance and stability, particularly on older Android versions. This prop is passed via `webViewProps` to the YoutubePlayer component.
```jsx
```
--------------------------------
### Render YouTube Video with Play/Pause and State Change Handling (JSX)
Source: https://github.com/lonelycpp/react-native-youtube-iframe/blob/master/docs/basic_usage.mdx
This snippet demonstrates how to embed a YouTube video using the YoutubePlayer component. It utilizes state to manage the video's playing status and includes an event handler for when the video playback state changes, specifically triggering an alert when the video ends. Dependencies include React, React Native components (Button, View, Alert), and the YoutubePlayer from 'react-native-youtube-iframe'.
```jsx
import React, { useState, useCallback, useRef } from "react";
import { Button, View, Alert } from "react-native";
import YoutubePlayer from "react-native-youtube-iframe";
export default function App() {
const [playing, setPlaying] = useState(false);
const onStateChange = useCallback((state) => {
if (state === "ended") {
setPlaying(false);
Alert.alert("video has finished playing!");
}
}, []);
const togglePlaying = useCallback(() => {
setPlaying((prev) => !prev);
}, []);
return (
);
}
```
--------------------------------
### Display YouTube Video Thumbnail and Title in React Native Component (JavaScript)
Source: https://context7.com/lonelycpp/react-native-youtube-iframe/llms.txt
A React Native component that displays a YouTube video's thumbnail and title using fetched metadata. It utilizes the `getYoutubeMeta` function and React hooks (`useState`, `useEffect`) to manage the loading state and display video information. Includes basic styling for the thumbnail and text elements.
```javascript
import React, { useState, useEffect } from 'react';
import { View, Text, Image, StyleSheet } from 'react-native';
import { getYoutubeMeta } from 'react-native-youtube-iframe';
const VideoPreview = ({ videoId }) => {
const [metadata, setMetadata] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
const loadMetadata = async () => {
try {
const data = await getYoutubeMeta(videoId);
setMetadata(data);
} catch (error) {
console.error('Failed to load metadata:', error);
} finally {
setLoading(false);
}
};
loadMetadata();
}, [videoId]);
if (loading) {
return Loading...;
}
if (!metadata) {
return Failed to load video metadata;
}
return (
{metadata.title}by {metadata.author_name}
);
};
const styles = StyleSheet.create({
container: { padding: 10 },
thumbnail: { width: '100%', height: 200, borderRadius: 8 },
title: { fontSize: 18, fontWeight: 'bold', marginTop: 10 },
author: { fontSize: 14, color: '#666', marginTop: 5 },
});
export default VideoPreview;
```
--------------------------------
### Player Events
Source: https://github.com/lonelycpp/react-native-youtube-iframe/blob/master/docs/props.mdx
This section covers various events that can be triggered by the YouTube player, providing information about errors, fullscreen status, and playback quality changes.
```APIDOC
## Player Events
### `onError`
This event fires if an error occurs in the player. The API will pass an error string to the event listener function.
- **Type**: `function(error: string)`
- **Possible errors**:
- `invalid_parameter`: The request contains an invalid parameter value.
- `HTML5_error`: The requested content cannot be played in an HTML5 player or another error related to the HTML5 player has occurred.
- `video_not_found`: The video requested was not found.
- `embed_not_allowed`: The owner of the requested video does not allow it to be played in embedded players.
### `onFullScreenChange`
This event fires whenever the player goes in or out of fullscreen mode with a boolean that identifies the new fullscreen status.
- **Type**: `function(status: string)`
- **Note**: Android only.
### `onPlaybackQualityChange`
This event fires whenever the video playback quality changes. It might signal a change in the viewer's playback environment.
- **Type**: `function(quality: string)`
- **Possible Quality values**:
- `small`
- `medium`
- `large`
- `hd720`
- `hd1080`
- `highres`
```
--------------------------------
### Monitor YouTube Player State and Errors in React Native
Source: https://context7.com/lonelycpp/react-native-youtube-iframe/llms.txt
This snippet demonstrates how to monitor the state of a YouTube player embedded in a React Native application. It uses the `react-native-youtube-iframe` component and its provided enums (`PLAYER_STATES`, `PLAYER_ERRORS`) to handle various playback events, errors, full-screen changes, and quality updates. The component's callbacks (`onChangeState`, `onError`, `onFullScreenChange`, `onPlaybackQualityChange`) are used to update the application's state and log relevant information.
```jsx
import React, { useState } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import YoutubeIframe, { PLAYER_STATES, PLAYER_ERRORS } from 'react-native-youtube-iframe';
const StateMonitor = () => {
const [currentState, setCurrentState] = useState(PLAYER_STATES.UNSTARTED);
const [errorMessage, setErrorMessage] = useState('');
const [isFullScreen, setIsFullScreen] = useState(false);
const [playbackQuality, setPlaybackQuality] = useState('');
const handleStateChange = (state) => {
setCurrentState(state);
console.log('State changed to:', state);
switch (state) {
case PLAYER_STATES.PLAYING:
console.log('Video is playing');
break;
case PLAYER_STATES.PAUSED:
console.log('Video is paused');
break;
case PLAYER_STATES.ENDED:
console.log('Video ended');
break;
case PLAYER_STATES.BUFFERING:
console.log('Video is buffering');
break;
case PLAYER_STATES.UNSTARTED:
console.log('Video not started');
break;
case PLAYER_STATES.VIDEO_CUED:
console.log('Video cued');
break;
}
};
const handleError = (error) => {
setErrorMessage(error);
console.error('Player error:', error);
if (error === PLAYER_ERRORS.VIDEO_NOT_FOUND) {
console.error('Video not found (404)');
} else if (error === PLAYER_ERRORS.EMBED_NOT_ALLOWED) {
console.error('Embedding not allowed by video owner');
} else if (error === PLAYER_ERRORS.INVALID_PARAMETER) {
console.error('Invalid parameter');
} else if (error === PLAYER_ERRORS.HTML5_ERROR) {
console.error('HTML5 player error');
}
};
return (
console.log('Playback rate:', rate)}
/>
Current State: {currentState}Full Screen: {isFullScreen.toString()}Quality: {playbackQuality}
{errorMessage ? (
Error: {errorMessage}
) : null}
);
};
const styles = StyleSheet.create({
container: { flex: 1, padding: 20 },
statusContainer: { marginTop: 20, padding: 15, backgroundColor: '#f5f5f5', borderRadius: 8 },
statusText: { fontSize: 16, marginBottom: 5 },
errorText: { fontSize: 16, color: 'red', marginTop: 10 },
});
export default StateMonitor;
```
--------------------------------
### getYoutubeMeta
Source: https://github.com/lonelycpp/react-native-youtube-iframe/blob/master/docs/module_methods.mdx
Fetches metadata for a given YouTube video ID using the oEmbed specification. This method returns a promise that resolves with the video's metadata.
```APIDOC
## getYoutubeMeta
### Description
Fetches metadata of a youtube video using the oEmbed Spec.
### Method
`getYoutubeMeta`
### Endpoint
N/A (This is a module method, not a REST endpoint)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```javascript
import { getYoutubeMeta } from 'react-native-youtube-iframe';
getYoutubeMeta('sNhhvQGsMEc').then(meta => {
console.log(meta.title);
});
```
### Response
#### Success Response (Promise resolves with youtubeMeta)
- **author_name** (String) - The name of the author/owner of the video.
- **author_url** (String) - youtube channel link of the video.
- **height** (Number) - The height in pixels required to display the HTML.
- **html** (String) - The HTML required to embed a video player.
- **provider_name** (String) - The name of the resource provider.
- **provider_url** (String) - The url of the resource provider.
- **thumbnail_height** (Number) - The height of the video thumbnail.
- **thumbnail_url** (String) - The url of the resource provider.
- **thumbnail_width** (Number) - The width of the video thumbnail.
- **title** (String) - youtube video title.
- **type** (String) - The oEmbed version number.
- **version** (String) - The resource type.
- **width** (Number) - The width in pixels required to display the HTML.
#### Response Example
```json
{
"author_name": "YouTube",
"author_url": "https://www.youtube.com",
"height": 270,
"html": "",
"provider_name": "YouTube",
"provider_url": "https://www.youtube.com",
"thumbnail_height": 360,
"thumbnail_url": "https://i.ytimg.com/vi/sNhhvQGsMEc/hqdefault.jpg",
"thumbnail_width": 480,
"title": "React Native YouTube Iframe",
"type": "video",
"version": "1.0",
"width": 480
}
```
```
--------------------------------
### Seek to Specific Time in Video - JavaScript
Source: https://github.com/lonelycpp/react-native-youtube-iframe/blob/master/docs/ref_methods.mdx
The `seekTo` function allows you to navigate to a specific point in the video. It takes the target time in seconds and a boolean `allowSeekAhead` as arguments. If the player is paused, it remains paused after seeking. If called during playback, the video will resume playing. Seeking occurs to the nearest keyframe unless the requested portion has already been buffered.
```javascript
playerRef.current?.seekTo(30, true);
```
--------------------------------
### Handle Fullscreen Changes and Control Player (JavaScript)
Source: https://github.com/lonelycpp/react-native-youtube-iframe/blob/master/website/static/iframe_v2.html
This snippet listens for fullscreen change events on the document and sends the fullscreen state to React Native. It also sets up a message listener to receive commands (play, pause, mute, unmute) from React Native and execute them on the player.
```javascript
var isFullScreen=!1;function onFullScreenChange(){isFullScreen=document.fullscreenElement||document.msFullscreenElement||document.mozFullScreenElement||document.webkitFullscreenElement,sendMessageToRN({eventType:"fullScreenChange",data:Boolean(isFullScreen)})}document.addEventListener("fullscreenchange",onFullScreenChange),document.addEventListener("msfullscreenchange",onFullScreenChange),document.addEventListener("mozfullscreenchange",onFullScreenChange),document.addEventListener("webkitfullscreenchange",onFullScreenChange),window.addEventListener("message",function(e){var{data:e}=e;switch(e){case"playVideo":player.playVideo();break;case"pauseVideo":player.pauseVideo();break;case"muteVideo":player.mute();break;case"unMuteVideo":player.unMute()}})
```
--------------------------------
### Player Functions API
Source: https://github.com/lonelycpp/react-native-youtube-iframe/blob/master/docs/ref_methods.mdx
This section details the player functions that can be called using a ref to the YoutubePlayer component. These functions allow for controlling playback, retrieving video information, and adjusting player settings.
```APIDOC
## Player Functions API
This document outlines the functions available to control the YouTube player instance programmatically via a ref.
### `getDuration`
- **Description**: Returns a promise that resolves to the total duration of the video in seconds. For live streams, it returns the elapsed time.
- **Method**: `getDuration()`
- **Parameters**: None
- **Returns**: `Promise`
### `getCurrentTime`
- **Description**: Returns a promise that resolves to the current playback time in seconds.
- **Method**: `getCurrentTime()`
- **Parameters**: None
- **Returns**: `Promise`
### `isMuted`
- **Description**: Returns a promise that resolves to a boolean indicating if the player is currently muted.
- **Method**: `isMuted()`
- **Parameters**: None
- **Returns**: `Promise`
### `getVolume`
- **Description**: Returns a promise that resolves to the current volume level (0-100).
- **Method**: `getVolume()`
- **Parameters**: None
- **Returns**: `Promise`
### `getPlaybackRate`
- **Description**: Returns a promise that resolves to the current playback rate of the video.
- **Method**: `getPlaybackRate()`
- **Parameters**: None
- **Returns**: `Promise`
### `getAvailablePlaybackRates`
- **Description**: Returns a promise that resolves to an array of available playback rates.
- **Method**: `getAvailablePlaybackRates()`
- **Parameters**: None
- **Returns**: `Promise>`
### `seekTo`
- **Description**: Seeks to a specified time in the video. If the player is paused, it remains paused. Otherwise, it plays the video.
- **Method**: `seekTo(seconds: Number, allowSeekAhead: Boolean)`
- **Parameters**:
- `seconds` (Number) - The time in seconds to seek to.
- `allowSeekAhead` (Boolean) - Whether to allow seeking ahead in the video.
- **Returns**: `Void`
### Basic Usage Example
```jsx
import React, { useRef } from 'react';
import YoutubePlayer from 'react-native-youtube-iframe';
const App = () => {
const playerRef = useRef();
return (
<>
{
playerRef.current?.getCurrentTime().then(currentTime => {
console.log({ currentTime });
});
}}
/>
>
);
};
```
```