media_session_dom1.html (2850B)
1 <html> 2 <head> 3 <title>MediaSessionDOMTest1</title> 4 </head> 5 <body> 6 <script> 7 function updatePositionState(event) { 8 if (event.target != active) { 9 return; 10 } 11 navigator.mediaSession.setPositionState({ 12 duration: parseFloat(event.target.duration), 13 position: parseFloat(event.target.currentTime), 14 playbackRate: 1, 15 }); 16 } 17 18 function updateMetadata() { 19 navigator.mediaSession.metadata = active.metadata; 20 } 21 22 function getTrack(offset) { 23 console.log("" + active.id + " " + offset); 24 const nextId = Math.min( 25 tracks.length - 1, 26 Math.max(0, parseInt(active.id) + offset) 27 ); 28 return tracks[nextId]; 29 } 30 31 navigator.mediaSession.setActionHandler("play", async () => { 32 updateMetadata(); 33 await active.play(); 34 }); 35 36 navigator.mediaSession.setActionHandler("pause", () => { 37 active.pause(); 38 }); 39 40 navigator.mediaSession.setActionHandler("previoustrack", () => { 41 active = getTrack(-1); 42 }); 43 44 navigator.mediaSession.setActionHandler("nexttrack", () => { 45 active = getTrack(1); 46 }); 47 48 const audio1 = document.createElement("audio"); 49 audio1.src = "audio/owl.mp3"; 50 audio1.addEventListener("timeupdate", updatePositionState); 51 audio1.metadata = new window.MediaMetadata({ 52 title: "hoot", 53 artist: "owl", 54 album: "hoots", 55 artwork: [ 56 { 57 src: "images/test.gif", 58 type: "image/gif", 59 sizes: "265x199", 60 }, 61 ], 62 }); 63 audio1.id = 0; 64 65 const audio2 = document.createElement("audio"); 66 audio2.src = "audio/owl.mp3"; 67 audio2.addEventListener("timeupdate", updatePositionState); 68 audio2.metadata = new window.MediaMetadata({ 69 title: "hoot2", 70 artist: "stillowl", 71 album: "dahoots", 72 artwork: [ 73 { 74 src: "images/test.gif", 75 type: "image/gif", 76 sizes: "265x199", 77 }, 78 ], 79 }); 80 audio2.id = 1; 81 82 const audio3 = document.createElement("audio"); 83 audio3.src = "audio/owl.mp3"; 84 audio3.addEventListener("timeupdate", updatePositionState); 85 audio3.metadata = new window.MediaMetadata({ 86 title: "hoot3", 87 artist: "immaowl", 88 album: "mahoots", 89 artwork: [ 90 { 91 src: "images/test.gif", 92 type: "image/gif", 93 sizes: "265x199", 94 }, 95 ], 96 }); 97 audio3.id = 2; 98 99 const tracks = [audio1, audio2, audio3]; 100 let active = audio1; 101 102 window.onload = async () => { 103 active = getTrack(0); 104 updateMetadata(); 105 await active.play(); 106 }; 107 </script> 108 </body> 109 </html>