Sling Academy
Home/JavaScript/Control Playback UI with the Media Session API in JavaScript

Control Playback UI with the Media Session API in JavaScript

Last updated: December 13, 2024

The Media Session API allows developers to control the playback experience on web pages, providing a standardized way to interact with media elements like audio or video. By integrating this API into your project, you can create rich user experiences that enable smooth control over media playback, even when the browser or app is not visible.

Getting Started with the Media Session API

To utilize the Media Session API, you'll need to ensure that your development environment or browser supports it. Popular browsers like Chrome, Firefox, and Edge already offer compatibility. The primary interface you'll interact with is navigator.mediaSession.

if ('mediaSession' in navigator) {
  console.log('Media Session API is supported!');
} else {
  console.error('Media Session API is not supported in this browser.');
}

The API provides control over metadata, playback state, and action handlers. Let’s look at setting up some of these components.

Setting Media Metadata

Metadata includes information about the media currently being played, which enriches the media experience by showing titles, artists, album art, and more on compatible devices or platforms.

navigator.mediaSession.metadata = new MediaMetadata({
  title: 'Amazing Song',
  artist: 'John Doe',
  album: 'Best Hits',
  artwork: [
    { src: 'album-artwork.png', sizes: '512x512', type: 'image/png' }
  ]
});

The metadata object enhances the user interface; for instance, it appears on media notifications in the Android system UI or a smart display device.

Handling Media Playback Actions

The Media Session API lets you define actions like play, pause, next track, and previous track. This is done using action handlers.

navigator.mediaSession.setActionHandler('play', function() {
  // Logic for Play action
  audioElement.play();
});

navigator.mediaSession.setActionHandler('pause', function() {
  // Logic for Pause action
  audioElement.pause();
});

navigator.mediaSession.setActionHandler('previoustrack', function() {
  // Logic for Previous Track action
  skipToPreviousTrack();
});

navigator.mediaSession.setActionHandler('nexttrack', function() {
  // Logic for Next Track action
  skipToNextTrack();
});

If your media has more specialized actions, like seeking through the media file, you can set additional handlers like 'seekbackward' or 'seekforward'.

Updating Playback State

The API provides a way to update the playback state, keeping user interfaces in sync with the actual playback.

navigator.mediaSession.playbackState = 'playing';
// or 'paused' or 'none'

Updating the playback state helps external devices or system UI display meaningful statuses to the end-user.

Conclusion

By using the Media Session API, web developers can enrich their media-driven applications or web pages, providing direct control over systematic elements like notification centers and smart assistants. It’s a powerful interface for improving how web media interacts with playback controls and user notifications on a system level, enhancing usability and experience.

Next Article: Define Custom Media Controls Using the JavaScript Media Session API

Previous Article: Integrate Real-Time AV Capture into Web Apps with JavaScript

Series: Web APIs – JavaScript Tutorials

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration