1. Core Concepts
  2. State Management

Core Concepts

State Management

In this section, we'll look at the API available for reading and updating media state.

Reading

You can retrieve a snapshot of the current media state like so:

        const media = document.querySelector('vds-media');

const {
  paused,
  playing,
  waiting,
  currentTime,
  // ...
} = media.state;

      

Subscribing

The <vds-media> element has a media store that keeps track of the running state of the player. The store enables you to subscribe directly to specific media state changes, rather than listening to potentially multiple DOM events and binding it yourself.

Tracking media state via events:

        const media = document.querySelector('vds-media');

let paused = true;

media.addEventListener('pause', () => {
  paused = true;
});

media.addEventListener('play', () => {
  paused = false;
});

      

Tracking media state via store subscription:

        const media = document.querySelector('vds-media');

const { paused } = media.store;

// The given function will re-run as the `paused` state changes.
const unsubscribe = paused.subscribe((paused) => {
  console.log('Paused:', paused);
});

unsubscribe();

      

Updating

The MediaRemoteControl class provides a simple facade for dispatching media request events. This can be used to request media playback to play/pause, change the current volume level, seek to a different time position, and other actions that change media state.

        import { MediaRemoteControl } from 'vidstack';

// 1. Create the media remote control.
const remote = new MediaRemoteControl();

// 2. Set a target element to dispatch media requests from.
const button = document.createElement('button');
remote.setTarget(button);

button.addEventListener('pointerup', (pointerEvent) => {
  // 3. Make a play request and pass the pointer event as the trigger.
  // Trigger events are optional - enables tracing event origin.
  remote.play(pointerEvent);
});

// 4. Destroy remote when no longer required.
remote.destroy();

      

Media Element

The MediaRemoteControl can attempt to find the nearest parent media element once a target has been attached like so:

        import { isHLSVideoElement, MediaRemoteControl } from 'vidstack';

// 1. Create the media remote control.
const remote = new MediaRemoteControl();

// 2. Set a target element to search from.
const button = document.querySelector('button');
remote.setTarget(button);

// 3. Find media element
const media = remote.getMedia(); // `MediaElement | null`

media?.onAttach(() => {
  if (isHLSVideoElement(media.provider)) {
    // ...
  }
});

// 4. Destroy remote when no longer required.
remote.destroy();