Getting Started
Ce contenu n'est pas encore disponible dans votre langue.
-
Install the package
Fenêtre de terminal npm i @capgo/capacitor-youtube-playerFenêtre de terminal pnpm add @capgo/capacitor-youtube-playerFenêtre de terminal yarn add @capgo/capacitor-youtube-playerFenêtre de terminal bun add @capgo/capacitor-youtube-player -
Sync with native projects
Fenêtre de terminal npx cap syncFenêtre de terminal pnpm cap syncFenêtre de terminal yarn cap syncFenêtre de terminal bunx cap sync
Basic Usage
Section titled “Basic Usage”import { YoutubePlayer } from '@capgo/capacitor-youtube-player';
// Initialize the playerconst result = await YoutubePlayer.initialize({ playerId: 'youtube-player', playerSize: { width: 640, height: 360 }, videoId: 'dQw4w9WgXcQ', fullscreen: false, playerVars: { autoplay: 1, controls: 1 }});
// Play videoawait YoutubePlayer.playVideo(result.player);
// Pause videoawait YoutubePlayer.pauseVideo(result.player);
// Listen to player eventsYoutubePlayer.addEventListener(result.player, 'onStateChange', (event) => { console.log('Player state:', event.data);});API Reference
Section titled “API Reference”initialize(options)
Section titled “initialize(options)”Initialize a YouTube player instance.
const { player, playerReady } = await YoutubePlayer.initialize({ playerId: 'my-player', playerSize: { width: 1280, height: 720 }, videoId: 'VIDEO_ID', fullscreen: false, playerVars: { autoplay: 0, controls: 1, rel: 0 }});Video Control Methods
Section titled “Video Control Methods”// Playawait YoutubePlayer.playVideo(playerId);
// Pauseawait YoutubePlayer.pauseVideo(playerId);
// Stopawait YoutubePlayer.stopVideo(playerId);
// Seek to timeawait YoutubePlayer.seekTo(playerId, seconds, allowSeekAhead);
// Load video by IDawait YoutubePlayer.loadVideoById(playerId, { videoId: 'VIDEO_ID' });
// Cue video (load without playing)await YoutubePlayer.cueVideoById(playerId, { videoId: 'VIDEO_ID' });Playlist Control
Section titled “Playlist Control”// Load playlistawait YoutubePlayer.loadPlaylist(playerId, { listType: 'playlist', list: 'PLAYLIST_ID'});
// Cue playlistawait YoutubePlayer.cuePlaylist(playerId, { playlist: ['VIDEO_ID_1', 'VIDEO_ID_2'], index: 0});
// Navigate playlistawait YoutubePlayer.nextVideo(playerId);await YoutubePlayer.previousVideo(playerId);await YoutubePlayer.playVideoAt(playerId, index);Audio Control
Section titled “Audio Control”// Mute/Unmuteawait YoutubePlayer.mute(playerId);await YoutubePlayer.unMute(playerId);
const { result } = await YoutubePlayer.isMuted(playerId);console.log('Muted:', result.value);
// Volume (0-100)await YoutubePlayer.setVolume(playerId, 50);const { result } = await YoutubePlayer.getVolume(playerId);Playback Control
Section titled “Playback Control”// Playback rateawait YoutubePlayer.setPlaybackRate(playerId, 1.5);const { result } = await YoutubePlayer.getPlaybackRate(playerId);
// Available ratesconst { result } = await YoutubePlayer.getAvailablePlaybackRates(playerId);console.log('Available rates:', result.value);
// Loop and shuffleawait YoutubePlayer.setLoop(playerId, true);await YoutubePlayer.setShuffle(playerId, true);Quality Control
Section titled “Quality Control”// Set qualityawait YoutubePlayer.setPlaybackQuality(playerId, 'hd720');
// Get current qualityconst { result } = await YoutubePlayer.getPlaybackQuality(playerId);
// Get available qualitiesconst { result } = await YoutubePlayer.getAvailableQualityLevels(playerId);Player Information
Section titled “Player Information”// Durationconst { result } = await YoutubePlayer.getDuration(playerId);
// Current timeconst { result } = await YoutubePlayer.getCurrentTime(playerId);
// Loaded fractionconst { result } = await YoutubePlayer.getVideoLoadedFraction(playerId);
// Player stateconst { result } = await YoutubePlayer.getPlayerState(playerId);
// Video URLconst { result } = await YoutubePlayer.getVideoUrl(playerId);Event Listeners
Section titled “Event Listeners”// State changeYoutubePlayer.addEventListener(playerId, 'onStateChange', (event) => { console.log('State:', event.data); // -1, 0, 1, 2, 3, 5});
// ReadyYoutubePlayer.addEventListener(playerId, 'onReady', (event) => { console.log('Player ready');});
// ErrorYoutubePlayer.addEventListener(playerId, 'onError', (event) => { console.error('Player error:', event.data);});
// Quality changeYoutubePlayer.addEventListener(playerId, 'onPlaybackQualityChange', (event) => { console.log('Quality:', event.data);});
// Rate changeYoutubePlayer.addEventListener(playerId, 'onPlaybackRateChange', (event) => { console.log('Rate:', event.data);});
// Remove listenerYoutubePlayer.removeEventListener(playerId, 'onStateChange', callback);Complete Example
Section titled “Complete Example”import { YoutubePlayer } from '@capgo/capacitor-youtube-player';
export class YouTubeService { private playerId: string | null = null;
async initPlayer(videoId: string) { try { const { player, playerReady } = await YoutubePlayer.initialize({ playerId: 'main-player', playerSize: { width: 1280, height: 720 }, videoId, fullscreen: false, playerVars: { autoplay: 0, controls: 1, modestbranding: 1, rel: 0 } });
this.playerId = player;
// Set up event listeners YoutubePlayer.addEventListener(player, 'onReady', () => { console.log('Player is ready'); });
YoutubePlayer.addEventListener(player, 'onStateChange', (event) => { this.handleStateChange(event.data); });
YoutubePlayer.addEventListener(player, 'onError', (event) => { console.error('YouTube error:', event.data); });
return player; } catch (error) { console.error('Failed to initialize player:', error); throw error; } }
private handleStateChange(state: number) { switch (state) { case -1: console.log('Unstarted'); break; case 0: console.log('Ended'); break; case 1: console.log('Playing'); break; case 2: console.log('Paused'); break; case 3: console.log('Buffering'); break; case 5: console.log('Video cued'); break; } }
async play() { if (!this.playerId) return; await YoutubePlayer.playVideo(this.playerId); }
async pause() { if (!this.playerId) return; await YoutubePlayer.pauseVideo(this.playerId); }
async loadVideo(videoId: string) { if (!this.playerId) return; await YoutubePlayer.loadVideoById(this.playerId, { videoId }); }
async loadPlaylist(playlistId: string) { if (!this.playerId) return; await YoutubePlayer.loadPlaylist(this.playerId, { listType: 'playlist', list: playlistId, index: 0 }); }
async setQuality(quality: 'small' | 'medium' | 'large' | 'hd720' | 'hd1080') { if (!this.playerId) return; await YoutubePlayer.setPlaybackQuality(this.playerId, quality); }
async getProgress() { if (!this.playerId) return { current: 0, duration: 0 };
const current = await YoutubePlayer.getCurrentTime(this.playerId); const duration = await YoutubePlayer.getDuration(this.playerId);
return { current: current.result.value, duration: duration.result.value }; }
async destroy() { if (!this.playerId) return; await YoutubePlayer.destroy(this.playerId); this.playerId = null; }}Player States
Section titled “Player States”| State | Value | Description |
|---|---|---|
| UNSTARTED | -1 | Video not started |
| ENDED | 0 | Video has ended |
| PLAYING | 1 | Video is playing |
| PAUSED | 2 | Video is paused |
| BUFFERING | 3 | Video is buffering |
| CUED | 5 | Video is cued |
Quality Levels
Section titled “Quality Levels”small: 240pmedium: 360plarge: 480phd720: 720phd1080: 1080phighres: >1080pdefault: Auto quality
Best Practices
Section titled “Best Practices”-
Initialize once Create player instance once and reuse it:
let player = await YoutubePlayer.initialize(options);// Reuse player for different videosawait YoutubePlayer.loadVideoById(player, { videoId: 'NEW_ID' }); -
Handle errors gracefully
YoutubePlayer.addEventListener(playerId, 'onError', (event) => {switch (event.data) {case 2:console.error('Invalid parameter');break;case 100:console.error('Video not found');break;case 101:case 150:console.error('Embedding not allowed');break;}}); -
Clean up Destroy player when component unmounts:
useEffect(() => {return () => {if (playerId) {YoutubePlayer.destroy(playerId);}};}, []); -
Respect user preferences
// Don't autoplay unless user initiatedplayerVars: {autoplay: 0} -
Monitor playback
setInterval(async () => {const time = await YoutubePlayer.getCurrentTime(playerId);updateProgressBar(time.result.value);}, 1000);
Platform Notes
Section titled “Platform Notes”- Works on iOS 9.0+
- Uses WKWebView with YouTube iframe API
- Fullscreen supported
Android
Section titled “Android”- Works on Android 5.0 (API 21)+
- Uses WebView with YouTube iframe API
- Fullscreen supported
- Direct YouTube iframe integration
- Full API support
- Best performance
Troubleshooting
Section titled “Troubleshooting”Player not loading:
- Check video ID is valid
- Verify internet connection
- Ensure YouTube embedding is allowed for the video
Events not firing:
- Make sure listeners are added after initialization
- Check player is ready before adding listeners
Quality issues:
- Check available quality levels first
- Some videos don’t support all qualities
- Quality changes may not be immediate