Getting Started
Este contenido aún no está disponible en tu idioma.
-
Install the plugin
Ventana de terminal npm i @capgo/capacitor-media-sessionVentana de terminal pnpm add @capgo/capacitor-media-sessionVentana de terminal yarn add @capgo/capacitor-media-sessionVentana de terminal bun add @capgo/capacitor-media-session -
Sync platforms
Ventana de terminal npx cap syncVentana de terminal pnpm cap syncVentana de terminal yarn cap syncVentana de terminal bunx cap sync
ℹ️ The Media Session API is available on Android (Chrome based browsers, WebView) and many desktop browsers. On unsupported platforms the calls resolve without taking effect, so guard your UI accordingly.
Publish metadata
Section titled “Publish metadata”import { MediaSession } from '@capgo/capacitor-media-session';
await MediaSession.setMetadata({ title: 'Weekly Tech Podcast', artist: 'Capgo Studio', album: 'Season 2', artwork: [ { src: 'https://cdn.example.com/covers/s02e05-512.png', sizes: '512x512', type: 'image/.png' }, ],});Update playback state
Section titled “Update playback state”await MediaSession.setPlaybackState({ playbackState: 'playing' });
// Pause later if neededawait MediaSession.setPlaybackState({ playbackState: 'paused' });Handle media actions
Section titled “Handle media actions”const pauseHandler = async () => { player.pause(); await MediaSession.setPlaybackState({ playbackState: 'paused' });};
await MediaSession.setActionHandler({ action: 'pause' }, pauseHandler);await MediaSession.setActionHandler({ action: 'play' }, async () => { await player.play(); await MediaSession.setPlaybackState({ playbackState: 'playing' });});
// Remove a handler when you dispose the playerawait MediaSession.setActionHandler({ action: 'pause' }, null);Keep position in sync
Section titled “Keep position in sync”const updatePosition = async () => { await MediaSession.setPositionState({ duration: player.duration, position: player.currentTime, playbackRate: player.playbackRate, });};
player.ontimeupdate = updatePosition;player.onratechange = updatePosition;Recommendations
Section titled “Recommendations”- Refresh metadata when the track changes so notifications and smart speakers stay up to date.
- Throttle position updates (e.g. every 250 ms) to avoid spamming the native layer.
- Always remove action handlers when tearing down a player instance to prevent accidental leakage.