Passer au contenu

Getting Started

Ce contenu n'est pas encore disponible dans votre langue.

  1. Install the plugin

    Fenêtre de terminal
    npm i @capgo/capacitor-media-session
  2. Sync platforms

    Fenêtre de terminal
    npx 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

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

await MediaSession.setPlaybackState({ playbackState: 'playing' });
// Pause later if needed
await MediaSession.setPlaybackState({ playbackState: 'paused' });

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 player
await MediaSession.setActionHandler({ action: 'pause' }, null);

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

  • 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.