<!DOCTYPE html>
<
html
lang
=
"en"
>
<
head
>
<
meta
charset
=
"UTF-8"
>
<
meta
name
=
"viewport"
content
=
"width=device-width, initial-scale=1.0"
>
<
title
>Media Session Example</
title
>
<
style
>
section {
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
}
h1 {
color: green;
}
h2 {
color: crimson;
}
</
style
>
</
head
>
<
body
>
<
section
>
<
h1
>
GeeksForGeeks | Media Session Example
</
h1
>
<
audio
id
=
"myAudio"
controls>
<
source
src
=
type
=
"audio/mp3"
>
Your browser does not support the audio Tag.
</
audio
>
<
h2
>Actions:</
h2
>
<
h3
id
=
"actions"
></
h3
>
</
section
>
<
script
>
// Get the element where actions will be displayed
let actions = document.getElementById('actions');
// Check if MediaSession is supported
if ('mediaSession' in navigator) {
// Associate MediaSession with the audio element
navigator.mediaSession.metadata = new MediaMetadata({
title: 'Geeks For Geeks',
artist: 'Geeks For Geeks',
album: 'Geeks For Geeks',
artwork: [
sizes: '192x192', type: 'image/jpg' },
sizes: '384x384', type: 'image/jpg' },
],
});
// Define action handlers for play, pause etc..
navigator.mediaSession.
setActionHandler('play', function () {
actions.innerText = "Clicked on Play button";
});
navigator.mediaSession.
setActionHandler('pause', function () {
actions.innerText = "Clicked on Pause button";
});
navigator.mediaSession.
setActionHandler('nexttrack', function () {
actions.innerText = "Clicked on Next Track button";
});
navigator.mediaSession.
setActionHandler("previoustrack", () => {
actions.innerText = "Clicked on Previous Track button";
});
navigator.mediaSession.
setActionHandler("seekforward", () => {
actions.innerText = "Clicked on Forward button";
});
navigator.mediaSession.
setActionHandler("seekbackward", () => {
actions.innerText = "Clicked on Backward button";
});
} else {
// Alert if MediaSession is not supported
alert('MediaSession is not supported in this browser.');
}
</
script
>
</
body
>
</
html
>