If you want the audio on your website to display song information such as the title and artist on the Notification Bar (similar to music player apps), you can use the Media Session API. This JavaScript API allows you to manage media-related metadata in web browsers.
Steps to Implement
Create the Audio File in HTML
Use the <audio>
tag to add an audio file to your webpage:
html<audio id="audio" controls> <source src="path/to/your-audio-file.mp3" type="audio/mpeg"> Your browser does not support the audio tag. </audio>
Set Metadata with JavaScript
Use the Media Session API to define metadata for the audio, such as the song title, artist name, and album artwork.
javascript// Select the Audio Element const audio = document.getElementById('audio'); // Check if the browser supports the Media Session API if ('mediaSession' in navigator) { navigator.mediaSession.metadata = new MediaMetadata({ title: 'Your Song Title', artist: 'Your Artist Name', album: 'Album Name (if any)', artwork: [ { src: 'path/to/your-album-artwork.jpg', sizes: '512x512', type: 'image/jpeg' } ] }); // Add controls (e.g., Play, Pause) navigator.mediaSession.setActionHandler('play', () => { audio.play(); }); navigator.mediaSession.setActionHandler('pause', () => { audio.pause(); }); }
Once you set navigator.mediaSession.metadata
, the defined metadata will appear in the system's Notification Bar (for browsers that support it, such as Chrome on Android).
Full example code:
html<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Media Metadata Example</title> </head> <body> <h1>Media Metadata Example</h1> <audio id="audio" controls> <source src="song.mp3" type="audio/mpeg"> Your browser does not support the audio tag. </audio> <script> const audio = document.getElementById('audio'); if ('mediaSession' in navigator) { navigator.mediaSession.metadata = new MediaMetadata({ title: 'My Song', artist: 'John Doe', album: 'My Album', artwork: [ { src: 'album-art.jpg', sizes: '512x512', type: 'image/jpeg' } ] }); navigator.mediaSession.setActionHandler('play', () => { audio.play(); }); navigator.mediaSession.setActionHandler('pause', () => { audio.pause(); }); } </script> </body> </html>
The Media Session API is not supported by all browsers. For instance, Safari may have some limitations.