feat(soundtrack): control playback through the Media Session API (#4904)

This commit is contained in:
Sam Dornan
2026-09-28 19:46:55 -04:00
committed by GitHub
parent 99675a4db5
commit 9798afdc7a
3 changed files with 531 additions and 10 deletions

View File

@@ -3,13 +3,14 @@
// card floats on desktop; on phones the top bar's NowPlayingPill opens it.
import type { Emitter } from "mitt";
import { storeToRefs } from "pinia";
import { inject, onBeforeUnmount, onMounted, ref, watch } from "vue";
import { computed, inject, onBeforeUnmount, onMounted, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import storePlaying from "@/stores/playing";
import useSoundtrackPlayer from "@/stores/soundtrackPlayer";
import type { Events } from "@/types/emitter";
import NowPlayingCard from "@/v2/components/Soundtrack/NowPlayingCard.vue";
import { useBreakpoint } from "@/v2/composables/useBreakpoint";
import { useMediaSession } from "@/v2/composables/useMediaSession";
import { useMiniPlayerVisible } from "@/v2/composables/useMiniPlayerVisible";
defineOptions({ inheritAttrs: false });
@@ -26,14 +27,16 @@ const audioEl = ref<HTMLAudioElement | null>(null);
// On phones the mini player lives in the top bar, which a running game hides,
// so the music pauses rather than play on with no controls.
watch([() => playingStore.stageActive, smAndDown], ([active, phone]) => {
if (active && phone) audioEl.value?.pause();
const musicBlocked = computed(
() => playingStore.stageActive && smAndDown.value,
);
watch(musicBlocked, (isBlocked) => {
if (isBlocked) audioEl.value?.pause();
});
useMediaSession(() => musicBlocked.value);
// Generation token — bumped every time we reassign `src`. Any async
// `play()` promise resolves against the token current when it was
// kicked off, so stale awaits from prior tracks don't clobber the
// current state. Same idiom as v1's mini player.
// Bumped on every `src` change, so a pending `play()` from an earlier track
// can't change the current track's state.
let loadToken = 0;
// Track loads, seeks and short stalls often resolve within a second; buffering
@@ -82,7 +85,7 @@ watch(track, async (t) => {
} catch {
if (token !== loadToken) return;
// Autoplay may be blocked; the user can hit play in the UI.
// Don't surface a snackbar for that — real load failures come
// Don't surface a snackbar for that; real load failures come
// through `@error`.
}
} else {
@@ -123,7 +126,7 @@ function onCanPlay() {
function onError() {
clearTimeout(bufferingTimer);
store.setError();
// Snackbar payload still uses v1's `snackbarShow` event shape —
// Snackbar payload still uses v1's `snackbarShow` event shape;
// when v1 is removed, switch to `useSnackbar()` here.
emitter?.emit("snackbarShow", {
msg: t("rom.cant-play-track"),
@@ -135,7 +138,7 @@ function onError() {
</script>
<template>
<!-- Persistent audio element — hidden, always mounted. -->
<!-- Persistent audio element: hidden, always mounted. -->
<!-- eslint-disable-next-line vuejs-accessibility/media-has-caption -->
<audio
ref="audioEl"

View File

@@ -0,0 +1,355 @@
import { createPinia, setActivePinia } from "pinia";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { effectScope, nextTick, type EffectScope } from "vue";
import useSoundtrackPlayer, {
type PlayerMeta,
type PlayerTrack,
} from "@/stores/soundtrackPlayer";
import { useMediaSession } from "@/v2/composables/useMediaSession";
class FakeMediaMetadata {
title: string;
artist: string;
album: string;
artwork: MediaImage[];
constructor(init: MediaMetadataInit = {}) {
this.title = init.title ?? "";
this.artist = init.artist ?? "";
this.album = init.album ?? "";
this.artwork = [...(init.artwork ?? [])];
}
}
class FakeMediaSession {
metadata: FakeMediaMetadata | null = null;
playbackState: MediaSessionPlaybackState = "none";
handlers = new Map<MediaSessionAction, MediaSessionActionHandler>();
setPositionState = vi.fn<(state?: MediaPositionState) => void>();
setActionHandler(
action: MediaSessionAction,
handler: MediaSessionActionHandler | null,
) {
if (action === "stop" && this.rejectStop) {
throw new TypeError("unsupported");
}
if (handler) this.handlers.set(action, handler);
else this.handlers.delete(action);
}
rejectStop = false;
fire(
action: MediaSessionAction,
details: Partial<MediaSessionActionDetails>,
) {
this.handlers.get(action)?.({ action, ...details });
}
}
function track(fileId: number): PlayerTrack {
return {
romId: 1,
fileId,
fileName: `track-${fileId}.mp3`,
url: `/api/roms/1/files/${fileId}/content/track-${fileId}.mp3`,
};
}
// A real element whose `paused` and `currentTime` change at once, while its
// events (and so the store) lag behind.
function fakeAudio() {
const el = document.createElement("audio");
const state = { paused: true, currentTime: 0 };
Object.defineProperty(el, "paused", { get: () => state.paused });
Object.defineProperty(el, "currentTime", {
get: () => state.currentTime,
set: (t: number) => {
state.currentTime = t;
},
});
const play = vi.spyOn(el, "play").mockImplementation(async () => {
state.paused = false;
});
const pause = vi.spyOn(el, "pause").mockImplementation(() => {
state.paused = true;
});
vi.spyOn(el, "load").mockImplementation(() => {});
return { el, state, play, pause };
}
describe("useMediaSession", () => {
let session: FakeMediaSession;
let scope: EffectScope;
beforeEach(() => {
setActivePinia(createPinia());
session = new FakeMediaSession();
Object.defineProperty(navigator, "mediaSession", {
configurable: true,
value: session,
});
vi.stubGlobal("MediaMetadata", FakeMediaMetadata);
scope = effectScope();
});
afterEach(() => {
scope.stop();
Reflect.deleteProperty(navigator, "mediaSession");
vi.unstubAllGlobals();
});
function start(blocked?: () => boolean) {
scope.run(() => useMediaSession(blocked));
}
it("sets metadata with the mini player's cover and clears it on stop", async () => {
const store = useSoundtrackPlayer();
start();
expect(session.metadata).toBeNull();
expect(session.playbackState).toBe("none");
const meta: PlayerMeta = {
title: "Green Hill Zone",
artist: "Masato Nakamura",
album: "Sonic the Hedgehog",
gameArtworkUrl: "/assets/romm/resources/roms/1/cover.png",
};
store.play(track(1), meta);
await nextTick();
expect(session.metadata).toEqual(
new FakeMediaMetadata({
title: "Green Hill Zone",
artist: "Masato Nakamura",
album: "Sonic the Hedgehog",
artwork: [{ src: "/assets/romm/resources/roms/1/cover.png" }],
}),
);
store.stop();
await nextTick();
expect(session.metadata).toBeNull();
expect(session.playbackState).toBe("none");
});
it("falls back to the file name and default cover without tags", async () => {
const store = useSoundtrackPlayer();
start();
store.play(track(2), {});
await nextTick();
expect(session.metadata?.title).toBe("track-2.mp3");
expect(session.metadata?.artwork).toEqual([
{ src: "/assets/default/album_cover.jpg" },
]);
});
it("keeps playbackState in sync with the player", async () => {
const store = useSoundtrackPlayer();
start();
store.play(track(1), {});
await nextTick();
expect(session.playbackState).toBe("paused");
store.setPlaying(true);
await nextTick();
expect(session.playbackState).toBe("playing");
store.setPlaying(false);
await nextTick();
expect(session.playbackState).toBe("paused");
});
it("routes play, pause and stop to the player", () => {
const store = useSoundtrackPlayer();
const audio = fakeAudio();
store.setAudioRef(audio.el);
const stop = vi.spyOn(store, "stop");
start();
session.fire("play", {});
expect(audio.play).not.toHaveBeenCalled();
store.play(track(1), {});
session.fire("pause", {});
expect(audio.pause).not.toHaveBeenCalled();
session.fire("play", {});
expect(audio.play).toHaveBeenCalledTimes(1);
session.fire("play", {});
expect(audio.play).toHaveBeenCalledTimes(1);
session.fire("stop", {});
expect(stop).toHaveBeenCalledOnce();
});
it("follows the element through presses faster than its events", () => {
const store = useSoundtrackPlayer();
const audio = fakeAudio();
audio.state.paused = false;
store.setAudioRef(audio.el);
store.play(track(1), {});
store.setPlaying(true);
start();
session.fire("pause", {});
session.fire("play", {});
expect(audio.pause).toHaveBeenCalledOnce();
expect(audio.play).toHaveBeenCalledOnce();
expect(audio.state.paused).toBe(false);
});
it("ignores play while the music is blocked, but still pauses", () => {
const store = useSoundtrackPlayer();
const audio = fakeAudio();
store.setAudioRef(audio.el);
store.play(track(1), {});
let blocked = true;
start(() => blocked);
session.fire("play", {});
expect(audio.play).not.toHaveBeenCalled();
blocked = false;
session.fire("play", {});
expect(audio.play).toHaveBeenCalledOnce();
blocked = true;
session.fire("pause", {});
expect(audio.pause).toHaveBeenCalledOnce();
});
it("seeks to a time and by an offset within the track", () => {
const store = useSoundtrackPlayer();
const seek = vi.spyOn(store, "seek").mockImplementation(() => {});
start();
store.play(track(1), {});
store.setDuration(100);
store.currentTime = 50;
session.fire("seekto", { seekTime: 42 });
expect(seek).toHaveBeenLastCalledWith(42);
session.fire("seekforward", {});
expect(seek).toHaveBeenLastCalledWith(60);
session.fire("seekbackward", { seekOffset: 5 });
expect(seek).toHaveBeenLastCalledWith(45);
session.fire("seekforward", { seekOffset: 80 });
expect(seek).toHaveBeenLastCalledWith(100);
session.fire("seekbackward", { seekOffset: 80 });
expect(seek).toHaveBeenLastCalledWith(0);
});
it("adds up seek presses that land before the next time update", () => {
const store = useSoundtrackPlayer();
const audio = fakeAudio();
audio.state.currentTime = 50;
store.setAudioRef(audio.el);
start();
store.play(track(1), {});
store.setDuration(100);
store.currentTime = 50;
session.fire("seekforward", {});
session.fire("seekforward", {});
expect(audio.state.currentTime).toBe(70);
expect(store.currentTime).toBe(50);
});
it("offers previous and next only when the queue has them", async () => {
const store = useSoundtrackPlayer();
const next = vi.spyOn(store, "next");
const previous = vi.spyOn(store, "previous");
start();
expect(session.handlers.has("previoustrack")).toBe(false);
expect(session.handlers.has("nexttrack")).toBe(false);
store.loadPlaylist([track(1), track(2)], {});
store.play(track(1), {});
await nextTick();
expect(session.handlers.has("previoustrack")).toBe(false);
expect(session.handlers.has("nexttrack")).toBe(true);
session.fire("nexttrack", {});
expect(next).toHaveBeenCalledOnce();
await nextTick();
expect(session.handlers.has("previoustrack")).toBe(true);
expect(session.handlers.has("nexttrack")).toBe(false);
session.fire("previoustrack", {});
expect(previous).toHaveBeenCalledOnce();
});
it("clamps the position state and skips unknown durations", async () => {
const store = useSoundtrackPlayer();
start();
store.play(track(1), {});
await nextTick();
expect(session.setPositionState).toHaveBeenLastCalledWith(undefined);
store.setDuration(Infinity);
await nextTick();
expect(session.setPositionState).toHaveBeenLastCalledWith(undefined);
store.setDuration(120);
store.currentTime = 30;
await nextTick();
expect(session.setPositionState).toHaveBeenLastCalledWith({
duration: 120,
position: 30,
});
store.currentTime = 150;
await nextTick();
expect(session.setPositionState).toHaveBeenLastCalledWith({
duration: 120,
position: 120,
});
});
it("survives a browser that rejects an action", () => {
session.rejectStop = true;
expect(() => start()).not.toThrow();
expect(session.handlers.has("play")).toBe(true);
expect(session.handlers.has("seekforward")).toBe(true);
});
it("clears handlers and metadata on dispose", async () => {
const store = useSoundtrackPlayer();
start();
store.loadPlaylist([track(1), track(2)], {});
store.play(track(1), {});
store.setPlaying(true);
await nextTick();
expect(session.handlers.size).toBeGreaterThan(0);
scope.stop();
expect(session.handlers.size).toBe(0);
expect(session.metadata).toBeNull();
expect(session.playbackState).toBe("none");
});
it("does nothing when the API is missing", async () => {
Reflect.deleteProperty(navigator, "mediaSession");
expect("mediaSession" in navigator).toBe(false);
const store = useSoundtrackPlayer();
expect(() => start()).not.toThrow();
store.play(track(1), {});
await nextTick();
expect(session.metadata).toBeNull();
expect(session.handlers.size).toBe(0);
});
it("sets no metadata when MediaMetadata is unavailable", async () => {
vi.stubGlobal("MediaMetadata", undefined);
const store = useSoundtrackPlayer();
start();
store.play(track(1), {});
store.setPlaying(true);
await nextTick();
expect(session.metadata).toBeNull();
expect(session.playbackState).toBe("playing");
});
});

View File

@@ -0,0 +1,163 @@
// Mirrors the soundtrack player into the Media Session API, so media keys, OS
// media overlays and lock screens show and control the playing track.
import { computed, onScopeDispose, watch } from "vue";
import useSoundtrackPlayer from "@/stores/soundtrackPlayer";
import { playerCoverUrl } from "@/v2/utils/soundtrackTracks";
const DEFAULT_SEEK_OFFSET_SECONDS = 10;
type HandledAction = Extract<
MediaSessionAction,
| "play"
| "pause"
| "stop"
| "previoustrack"
| "nexttrack"
| "seekto"
| "seekbackward"
| "seekforward"
>;
// Registered only while the queue has a track in that direction.
const QUEUE_ACTIONS = new Set<HandledAction>(["previoustrack", "nexttrack"]);
function mediaSession(): MediaSession | null {
return typeof navigator !== "undefined" && "mediaSession" in navigator
? navigator.mediaSession
: null;
}
// Browsers throw for actions they don't support.
function setHandler(
session: MediaSession,
action: MediaSessionAction,
handler: MediaSessionActionHandler | null,
) {
try {
session.setActionHandler(action, handler);
} catch {
// unsupported action
}
}
function setPosition(session: MediaSession, state?: MediaPositionState) {
if (typeof session.setPositionState !== "function") return;
try {
session.setPositionState(state);
} catch {
// rejected position state
}
}
/**
* Args:
* blocked: true while the music must stay paused, so the play key is ignored.
*/
export function useMediaSession(blocked: () => boolean = () => false): void {
const session = mediaSession();
if (!session) return;
const store = useSoundtrackPlayer();
// The element's paused state changes before its events update the store.
function playOrPause(play: boolean) {
const el = store.audioRef;
if (!store.track || !el || el.paused !== play) return;
if (play && blocked()) return;
store.togglePlayPause();
}
function seekBy(offset: number) {
const from = store.audioRef?.currentTime ?? store.currentTime;
const target = from + offset;
const max = store.duration > 0 ? store.duration : Infinity;
store.seek(Math.min(max, Math.max(0, target)));
}
const handlers: Record<HandledAction, MediaSessionActionHandler> = {
play: () => playOrPause(true),
pause: () => playOrPause(false),
stop: () => store.stop(),
previoustrack: () => store.previous(),
nexttrack: () => store.next(),
seekto: (details) => {
if (details.seekTime != null) store.seek(details.seekTime);
},
seekbackward: (details) =>
seekBy(-(details.seekOffset ?? DEFAULT_SEEK_OFFSET_SECONDS)),
seekforward: (details) =>
seekBy(details.seekOffset ?? DEFAULT_SEEK_OFFSET_SECONDS),
};
const actions = Object.keys(handlers) as HandledAction[];
for (const action of actions) {
if (!QUEUE_ACTIONS.has(action)) {
setHandler(session, action, handlers[action]);
}
}
watch(
() => store.hasPrevious,
(has) =>
setHandler(session, "previoustrack", has ? handlers.previoustrack : null),
{ immediate: true },
);
watch(
() => store.hasNext,
(has) => setHandler(session, "nexttrack", has ? handlers.nexttrack : null),
{ immediate: true },
);
const metadata = computed<MediaMetadataInit | null>(() => {
if (!store.track) return null;
return {
title: store.meta.title || store.track.fileName,
artist: store.meta.artist,
album: store.meta.album,
artwork: [{ src: playerCoverUrl(store.meta) }],
};
});
watch(
metadata,
(init) => {
session.metadata =
init && typeof MediaMetadata !== "undefined"
? new MediaMetadata(init)
: null;
},
{ immediate: true },
);
watch(
() => (store.track ? (store.isPlaying ? "playing" : "paused") : "none"),
(state) => {
session.playbackState = state;
},
{ immediate: true },
);
watch(
() => [store.track, store.duration, store.currentTime] as const,
([track, duration, position]) => {
if (!track || !Number.isFinite(duration) || duration <= 0) {
setPosition(session);
return;
}
setPosition(session, {
duration,
position: Number.isFinite(position)
? Math.min(duration, Math.max(0, position))
: 0,
});
},
{ immediate: true },
);
onScopeDispose(() => {
for (const action of actions) setHandler(session, action, null);
session.metadata = null;
session.playbackState = "none";
setPosition(session);
});
}