Iniziare
-
Installa il pacchetto
Terminal window npm i @capgo/capacitor-youtube-playerTerminal window pnpm add @capgo/capacitor-youtube-playerTerminal window yarn add @capgo/capacitor-youtube-playerTerminal window bun add @capgo/capacitor-youtube-player -
Sincronizzazione con progetti nativi
Terminal window npx cap syncTerminal window pnpm cap syncTerminal window yarn cap syncTerminal window bunx cap sync
Utilizzo di base
Section titled “Utilizzo di base”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 Riferimento
Section titled “API Riferimento”inizializza(opzioni)
Section titled “inizializza(opzioni)”Inizializza un’istanza del player YouTube.
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 }});Metodi di controllo video
Section titled “Metodi di controllo video”// 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' });Controllo della playlist
Section titled “Controllo della playlist”// 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);Controllo dell’audio
Section titled “Controllo dell’audio”// 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);Controllo della riproduzione
Section titled “Controllo della riproduzione”// 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);Controllo qualità
Section titled “Controllo qualità”// Set qualityawait YoutubePlayer.setPlaybackQuality(playerId, 'hd720');
// Get current qualityconst { result } = await YoutubePlayer.getPlaybackQuality(playerId);
// Get available qualitiesconst { result } = await YoutubePlayer.getAvailableQualityLevels(playerId);Informazioni sul giocatore
Section titled “Informazioni sul giocatore”// 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);Ascoltatori di eventi
Section titled “Ascoltatori di eventi”// 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);Esempio completo
Section titled “Esempio completo”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; }}Stati del giocatore
Section titled “Stati del giocatore”| Stato | Valore | Descrizione |
|---|---|---|
| NON INIZIATO | -1 | Video non avviato |
| FINITO | 0 | Il video è terminato |
| GIOCANDO | 1 | Il video è in riproduzione |
| IN PAUSA | 2 | Il video è in pausa |
| BUFFER | 3 | Il video è in buffering |
| CUED | 5 | Il video è suggerito |
Livelli di qualità
Section titled “Livelli di qualità”small: 240pmedium: 360plarge: 480phd720: 720phd1080: 1080phighres: >1080pdefault: qualità automatica
Migliori pratiche
Section titled “Migliori pratiche”-
Inizializza una volta Crea l’istanza del lettore una volta e riutilizzala:
let player = await YoutubePlayer.initialize(options);// Reuse player for different videosawait YoutubePlayer.loadVideoById(player, { videoId: 'NEW_ID' }); -
Gestire gli errori con garbo
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;}}); -
Pulisci Distruggi il giocatore quando il componente viene smontato:
useEffect(() => {return () => {if (playerId) {YoutubePlayer.destroy(playerId);}};}, []); -
Rispetta le preferenze dell’utente
// Don't autoplay unless user initiatedplayerVars: {autoplay: 0} -
Monitora la riproduzione
setInterval(async () => {const time = await YoutubePlayer.getCurrentTime(playerId);updateProgressBar(time.result.value);}, 1000);
Note sulla piattaforma
Section titled “Note sulla piattaforma”- Funziona su iOS 9.0+
- Utilizza WKWebView con iframe YouTube API
- Supporta lo schermo intero
Android
Section titled “Android”- Funziona su Android 5.0 (API 21)+
- Utilizza WebView con iframe YouTube API
- Supporta lo schermo intero
- Integrazione iframe diretta di YouTube
- Supporto completo per API
- Migliori prestazioni
Risoluzione dei problemi
Section titled “Risoluzione dei problemi”Il giocatore non si carica:
- Verifica che l’ID video sia valido
- Verificare la connessione Internet
- Assicurati che l’incorporamento su YouTube sia consentito per il video
Eventi non attivati:
- Assicurati che gli ascoltatori vengano aggiunti dopo l’inizializzazione
- Controlla che il player sia pronto prima di aggiungere ascoltatori
Problemi di qualità:
- Controlla prima i livelli di qualità disponibili
- Alcuni video non supportano tutte le qualità
- I cambiamenti di qualità potrebbero non essere immediati