A World Radio in Pure Frontend: Stateful URLs, Zero Backend, and Why Software Got So Complicated
How easy it is to build a global internet radio player with zero backend—using localStorage, compressed stateful URLs, and mobile Media Session controls—and why modern software rarely needs the complexity we're sold.
I’ve always wanted a simple internet radio player: pick a country, search for a station, star a few favorites, maybe drop in a custom stream URL or .m3u playlist, and hit play.
No account wall. No “sign in with Google to save your favorites.” No 40 MB app download.
So I built one—embedded right below—with zero backend servers, zero databases, and zero telemetry.
1. Radio: How Easy It Is (And the Frontend Strength Nobody Uses)
Building a global radio player in 2026 takes surprisingly little code:
- Playback: The browser’s native
<audio>element handles Icecast/Shoutcast MP3, AAC, and OGG streams directly—plus a tinyhls.jsfallback for.m3u8streams on browsers that don’t support HLS natively. Your server never touches a single byte of audio. - Global Directory: The open-source Radio Browser network exposes a free, CORS-enabled JSON API with tens of thousands of stations grouped by country (filtered to
https://streams so nothing breaks mixed-content rules). - Custom Stations & Playlists: Users can paste any
https://stream URL, or import a.json,.m3u, or.plsplaylist from a CORS-friendly host (like GitHub Raw) or by pasting raw playlist text directly.
That’s it. No audio proxy, no transcoding fleet, no auth microservice.
Yet almost every commercial radio or media product refuses to stop there. Instead, they trade away the browser’s natural strengths for information collection or misguided UX—forcing you to create an account just to bookmark three stations, wrapping a simple audio stream inside an Electron/native shell, or routing every click through a backend database so they can build a listening profile.
2. UX: The Many Ways You Can “Deliver” a Product
When you stop assuming every feature needs a database row, you unlock much lighter, faster ways to deliver a product to users:
localStorage as a Personal Database
Your favorites and custom imported stations belong to you, on your device. Storing them in localStorage means instant reads, zero latency, zero server bills, and complete privacy.
Stateful URLs: Bookmarkable on Every Change
Every action you take in the player—switching tabs, picking a country, typing a search query, starring a station, or adding custom stream URLs—immediately updates the browser’s URL via history.replaceState:
- Readable filters live in query parameters (
?view=countries&country=JP&q=jazz). - Richer state (favorites, custom stations, and active station ID) is compressed client-side using the browser’s built-in
CompressionStream('deflate-raw')and stored in the URL hash (#s=...).
Because the URL is the state, bookmarking the page or sending the link to a friend reproduces your exact setup—no “Share Playlist” backend endpoint required.
Crossover to Mobile Without an App Store
The web platform already bridges the gap to mobile hardware:
- Responsive layout adapts cleanly from desktop to phone screens.
navigator.mediaSessionintegrates the<audio>stream with iOS Lock Screen, Android notifications, Bluetooth headphones, and car dashboards—displaying the station name, country, and native play/pause controls.- Bookmark / Add to Home Screen plus a stateful URL gives you an instant “installed” experience with zero App Store review cycles.
3. Do We Really Need More Than This?!
You have to wonder why so many software solutions are orders of magnitude more complex than this.
Years ago, there was a legitimate excuse: the web platform wasn’t strong enough. Browsers lacked reliable local persistence, native compression streams, media session hardware hooks, and fast JS runtimes—so teams reached for heavy backends and native wrappers out of necessity.
That limitation is gone. Modern browsers can stream media, compress state, talk to lock-screen hardware, persist data locally, and even run WebAssembly and WebGPU AI models without a server in sight.
So when a simple tool today demands an account, a cloud database, a native app install, and a tracking SDK just to play a stream and remember your favorites, you have to ask: is it a technical requirement, or is it just the desire to collect information about you?
Unclear. Either way, try the live radio below—and check the source code underneath to see how little it actually takes.
Add Station or Import List
The Code
export type RadioViewMode = 'featured' | 'countries' | 'favorites' | 'custom';
export interface RadioStation {
id: string;
name: string;
url: string;
country: string;
countryCode: string;
tags: string[];
favicon?: string;
codec?: string;
bitrate?: number;
source?: 'curated' | 'radiobrowser' | 'custom';
}
export interface RadioCountry {
name: string;
code: string;
stationCount: number;
}
export interface RadioPersistedState {
view: RadioViewMode;
country: string;
query: string;
playingId: string | null;
favorites: RadioStation[];
customStations: RadioStation[];
listUrls: string[];
}import type { RadioStation } from './types';
/**
* Curated starter stations using reliable HTTPS streams so the player
* works immediately on load with zero external API latency.
*/
export const CURATED_STATIONS: RadioStation[] = [
{
id: 'curated-somafm-groovesalad',
name: 'SomaFM: Groove Salad',
url: 'https://ice1.somafm.com/groovesalad-128-mp3',
country: 'United States',
countryCode: 'US',
tags: ['ambient', 'downtempo', 'chill'],
codec: 'MP3',
bitrate: 128,
source: 'curated',
},
{
id: 'curated-somafm-defcon',
name: 'SomaFM: DEF CON Radio',
url: 'https://ice1.somafm.com/defcon-128-mp3',
country: 'United States',
countryCode: 'US',
tags: ['electronic', 'coding', 'hacker'],
codec: 'MP3',
bitrate: 128,
source: 'curated',
},
{
id: 'curated-somafm-dronezone',
name: 'SomaFM: Drone Zone',
url: 'https://ice1.somafm.com/dronezone-128-mp3',
country: 'United States',
countryCode: 'US',
tags: ['ambient', 'focus', 'space'],
codec: 'MP3',
bitrate: 128,
source: 'curated',
},
{
id: 'curated-nightride-fm',
name: 'Nightride FM',
url: 'https://stream.nightride.fm/nightride.mp3',
country: 'United States',
countryCode: 'US',
tags: ['synthwave', 'retrowave', 'electronic'],
codec: 'MP3',
bitrate: 128,
source: 'curated',
},
{
id: 'curated-fip-france',
name: 'FIP (Radio France)',
url: 'https://icecast.radiofrance.fr/fip-midfi.mp3',
country: 'France',
countryCode: 'FR',
tags: ['eclectic', 'jazz', 'world'],
codec: 'MP3',
bitrate: 128,
source: 'curated',
},
{
id: 'curated-nts-1',
name: 'NTS Radio 1',
url: 'https://stream-relay-geo.ntslive.net/stream',
country: 'United Kingdom',
countryCode: 'GB',
tags: ['underground', 'electronic', 'experimental'],
codec: 'MP3',
bitrate: 128,
source: 'curated',
},
{
id: 'curated-radio-paradise',
name: 'Radio Paradise (Main Mix)',
url: 'https://stream.radioparadise.com/aac-128',
country: 'United States',
countryCode: 'US',
tags: ['eclectic', 'rock', 'indie'],
codec: 'AAC',
bitrate: 128,
source: 'curated',
},
{
id: 'curated-swiss-jazz',
name: 'Radio Swiss Jazz',
url: 'https://stream.srg-ssr.ch/m/rsj/mp3_128',
country: 'Switzerland',
countryCode: 'CH',
tags: ['jazz', 'soul', 'blues'],
codec: 'MP3',
bitrate: 128,
source: 'curated',
},
{
id: 'curated-kexp-seattle',
name: 'KEXP 90.3 FM Seattle',
url: 'https://kexp-mp3-128.streamguys1.com/kexp128.mp3',
country: 'United States',
countryCode: 'US',
tags: ['indie', 'alternative', 'live'],
codec: 'MP3',
bitrate: 128,
source: 'curated',
},
];import type { RadioCountry, RadioStation } from './types';
const API_MIRRORS = [
'https://de1.api.radio-browser.info',
'https://fr1.api.radio-browser.info',
'https://nl1.api.radio-browser.info',
];
async function fetchFromMirrors<T>(path: string, signal?: AbortSignal): Promise<T> {
let lastError: unknown;
for (const base of API_MIRRORS) {
try {
const res = await fetch(`${base}${path}`, {
headers: { Accept: 'application/json' },
signal,
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return (await res.json()) as T;
} catch (err) {
if ((err as Error)?.name === 'AbortError') throw err;
lastError = err;
}
}
throw lastError instanceof Error ? lastError : new Error('All Radio Browser mirrors failed');
}
export async function fetchCountries(signal?: AbortSignal): Promise<RadioCountry[]> {
const raw = await fetchFromMirrors<Array<{ name: string; iso_3166_1: string; stationcount: number }>>(
'/json/countries?order=stationcount&reverse=true&hidebroken=true',
signal,
);
const byCode = new Map<string, RadioCountry>();
for (const item of raw) {
const code = (item.iso_3166_1 || '').trim().toUpperCase();
const name = (item.name || '').trim();
if (!code || !name || item.stationcount < 1) continue;
const existing = byCode.get(code);
if (!existing || item.stationcount > existing.stationCount) {
byCode.set(code, { name, code, stationCount: item.stationcount });
}
}
return Array.from(byCode.values()).sort((a, b) => b.stationCount - a.stationCount);
}
interface RawStation {
stationuuid: string;
name: string;
url: string;
url_resolved: string;
country: string;
countrycode: string;
tags: string;
favicon: string;
codec: string;
bitrate: number;
}
export async function searchStations(
opts: { countryCode?: string; query?: string; limit?: number },
signal?: AbortSignal,
): Promise<RadioStation[]> {
const params = new URLSearchParams({
hidebroken: 'true',
order: 'votes',
reverse: 'true',
limit: String(opts.limit || 60),
});
if (opts.countryCode) params.set('countrycode', opts.countryCode.toUpperCase());
if (opts.query?.trim()) params.set('name', opts.query.trim());
const raw = await fetchFromMirrors<RawStation[]>(`/json/stations/search?${params.toString()}`, signal);
const seenUrls = new Set<string>();
const stations: RadioStation[] = [];
for (const item of raw) {
const streamUrl = (item.url_resolved || item.url || '').trim();
// Enforce HTTPS-only streams to avoid mixed-content blocks on HTTPS sites
if (!streamUrl.startsWith('https://')) continue;
if (seenUrls.has(streamUrl)) continue;
seenUrls.add(streamUrl);
stations.push({
id: `rb-${item.stationuuid}`,
name: (item.name || 'Untitled Station').trim(),
url: streamUrl,
country: (item.country || '').trim(),
countryCode: (item.countrycode || '').trim().toUpperCase(),
tags: (item.tags || '')
.split(',')
.map((t) => t.trim())
.filter(Boolean)
.slice(0, 4),
favicon: item.favicon?.startsWith('https://') ? item.favicon : undefined,
codec: item.codec || undefined,
bitrate: item.bitrate || undefined,
source: 'radiobrowser',
});
}
return stations;
}import type { RadioStation } from './types';
function hashId(input: string): string {
let h = 2166136261;
for (let i = 0; i < input.length; i++) {
h ^= input.charCodeAt(i);
h = Math.imul(h, 16777619);
}
return `custom-${(h >>> 0).toString(36)}`;
}
function normalizeHttpsUrl(raw: string): string | null {
const trimmed = (raw || '').trim();
if (!trimmed.startsWith('https://')) return null;
try {
return new URL(trimmed).toString();
} catch {
return null;
}
}
export function createCustomStation(opts: {
url: string;
name?: string;
country?: string;
tags?: string[];
}): RadioStation | null {
const cleanUrl = normalizeHttpsUrl(opts.url);
if (!cleanUrl) return null;
let fallbackName = 'Custom Station';
try {
fallbackName = new URL(cleanUrl).hostname.replace(/^www\./, '');
} catch {}
return {
id: hashId(cleanUrl),
name: (opts.name || '').trim() || fallbackName,
url: cleanUrl,
country: (opts.country || '').trim() || 'Custom',
countryCode: '',
tags: (opts.tags || ['custom']).filter(Boolean).slice(0, 4),
source: 'custom',
};
}
function parseJsonCatalog(text: string): RadioStation[] {
const parsed = JSON.parse(text);
const items: any[] = Array.isArray(parsed)
? parsed
: Array.isArray(parsed?.stations)
? parsed.stations
: [];
const stations: RadioStation[] = [];
for (const item of items) {
const rawUrl = item?.url_resolved || item?.url || item?.stream || item?.stream_url || '';
const tags = Array.isArray(item?.tags)
? item.tags.map(String)
: typeof item?.genre === 'string'
? item.genre.split(',')
: typeof item?.tags === 'string'
? item.tags.split(',')
: [];
const station = createCustomStation({
url: String(rawUrl),
name: item?.name || item?.title,
country: item?.country || item?.country_code || item?.countryCode || 'Imported',
tags: tags.map((t: string) => t.trim()).filter(Boolean),
});
if (station) stations.push(station);
}
return stations;
}
function parseM3u(text: string): RadioStation[] {
const lines = text.split(/\r?\n/).map((l) => l.trim()).filter(Boolean);
const stations: RadioStation[] = [];
let pendingTitle = '';
for (const line of lines) {
if (line.startsWith('#EXTINF:')) {
const commaIdx = line.indexOf(',');
pendingTitle = commaIdx >= 0 ? line.slice(commaIdx + 1).trim() : '';
} else if (!line.startsWith('#')) {
const station = createCustomStation({
url: line,
name: pendingTitle || undefined,
country: 'Imported M3U',
tags: ['m3u'],
});
if (station) stations.push(station);
pendingTitle = '';
}
}
return stations;
}
function parsePls(text: string): RadioStation[] {
const files = new Map<string, string>();
const titles = new Map<string, string>();
for (const rawLine of text.split(/\r?\n/)) {
const line = rawLine.trim();
const fileMatch = /^File(\d+)=(.+)$/i.exec(line);
if (fileMatch) files.set(fileMatch[1], fileMatch[2].trim());
const titleMatch = /^Title(\d+)=(.+)$/i.exec(line);
if (titleMatch) titles.set(titleMatch[1], titleMatch[2].trim());
}
const stations: RadioStation[] = [];
for (const [idx, url] of files.entries()) {
const station = createCustomStation({
url,
name: titles.get(idx),
country: 'Imported PLS',
tags: ['pls'],
});
if (station) stations.push(station);
}
return stations;
}
export function parseStationListText(text: string): RadioStation[] {
const trimmed = (text || '').trim();
if (!trimmed) return [];
if (trimmed.startsWith('{') || trimmed.startsWith('[')) {
return parseJsonCatalog(trimmed);
}
if (/\[playlist\]/i.test(trimmed) || /^File\d+=/im.test(trimmed)) {
return parsePls(trimmed);
}
return parseM3u(trimmed);
}
export async function fetchStationListFromUrl(listUrl: string): Promise<RadioStation[]> {
const cleanUrl = normalizeHttpsUrl(listUrl);
if (!cleanUrl) {
throw new Error('Playlist URL must start with https://');
}
const res = await fetch(cleanUrl);
if (!res.ok) {
throw new Error(`Failed to fetch list (HTTP ${res.status})`);
}
const text = await res.text();
const stations = parseStationListText(text);
if (stations.length === 0) {
throw new Error('No valid HTTPS streams found in that list.');
}
return stations;
}import type { RadioPersistedState, RadioStation, RadioViewMode } from './types';
const STORAGE_KEY = 'mograblog_world_radio_v1';
export const DEFAULT_RADIO_STATE: RadioPersistedState = {
view: 'featured',
country: '',
query: '',
playingId: null,
favorites: [],
customStations: [],
listUrls: [],
};
function toBase64Url(bytes: Uint8Array): string {
let binary = '';
for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}
function fromBase64Url(b64: string): Uint8Array {
const padded = b64.replace(/-/g, '+').replace(/_/g, '/') + '==='.slice((b64.length + 3) % 4);
const binary = atob(padded);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
return bytes;
}
async function compressString(input: string): Promise<string> {
const encoded = new TextEncoder().encode(input);
if (typeof CompressionStream === 'undefined') {
return `u:${toBase64Url(encoded)}`;
}
const cs = new CompressionStream('deflate-raw');
const writer = cs.writable.getWriter();
writer.write(encoded);
writer.close();
const buf = await new Response(cs.readable).arrayBuffer();
return `z:${toBase64Url(new Uint8Array(buf))}`;
}
async function decompressString(token: string): Promise<string> {
const isCompressed = token.startsWith('z:');
const raw = token.startsWith('z:') || token.startsWith('u:') ? token.slice(2) : token;
const bytes = fromBase64Url(raw);
if (!isCompressed || typeof DecompressionStream === 'undefined') {
return new TextDecoder().decode(bytes);
}
const ds = new DecompressionStream('deflate-raw');
const writer = ds.writable.getWriter();
writer.write(bytes as unknown as BufferSource);
writer.close();
const buf = await new Response(ds.readable).arrayBuffer();
return new TextDecoder().decode(buf);
}
export function loadLocalState(): Partial<RadioPersistedState> {
try {
const raw = localStorage.getItem(STORAGE_KEY);
if (!raw) return {};
const parsed = JSON.parse(raw);
return parsed && typeof parsed === 'object' ? parsed : {};
} catch {
return {};
}
}
export function saveLocalState(state: RadioPersistedState): void {
try {
localStorage.setItem(STORAGE_KEY, JSON.stringify(state));
} catch {
// Ignore quota errors
}
}
function sanitizeStations(list: unknown): RadioStation[] {
if (!Array.isArray(list)) return [];
return list.filter(
(s): s is RadioStation =>
Boolean(s && typeof s === 'object' && typeof s.id === 'string' && typeof s.url === 'string' && s.url.startsWith('https://')),
);
}
export async function loadInitialState(): Promise<RadioPersistedState> {
const local = loadLocalState();
const merged: RadioPersistedState = {
view: (local.view as RadioViewMode) || 'featured',
country: typeof local.country === 'string' ? local.country : '',
query: typeof local.query === 'string' ? local.query : '',
playingId: typeof local.playingId === 'string' ? local.playingId : null,
favorites: sanitizeStations(local.favorites),
customStations: sanitizeStations(local.customStations),
listUrls: Array.isArray(local.listUrls) ? local.listUrls.filter((u): u is string => typeof u === 'string') : [],
};
if (typeof window === 'undefined') return merged;
const url = new URL(window.location.href);
const hash = url.hash || '';
const stateMatch = /[#&]s=([^&]+)/.exec(hash);
if (stateMatch?.[1]) {
try {
const json = await decompressString(decodeURIComponent(stateMatch[1]));
const fromUrl = JSON.parse(json) as Partial<RadioPersistedState>;
if (fromUrl.view) merged.view = fromUrl.view;
if (typeof fromUrl.country === 'string') merged.country = fromUrl.country;
if (typeof fromUrl.query === 'string') merged.query = fromUrl.query;
if (typeof fromUrl.playingId === 'string' || fromUrl.playingId === null) merged.playingId = fromUrl.playingId;
const urlFavs = sanitizeStations(fromUrl.favorites);
if (urlFavs.length > 0) {
const byId = new Map(merged.favorites.map((s) => [s.id, s]));
urlFavs.forEach((s) => byId.set(s.id, s));
merged.favorites = Array.from(byId.values());
}
const urlCustom = sanitizeStations(fromUrl.customStations);
if (urlCustom.length > 0) {
const byId = new Map(merged.customStations.map((s) => [s.id, s]));
urlCustom.forEach((s) => byId.set(s.id, s));
merged.customStations = Array.from(byId.values());
}
if (Array.isArray(fromUrl.listUrls) && fromUrl.listUrls.length > 0) {
merged.listUrls = Array.from(new Set([...merged.listUrls, ...fromUrl.listUrls]));
}
} catch {
// Ignore malformed hash state
}
}
// Also honor readable query parameters if present
const qView = url.searchParams.get('view') as RadioViewMode | null;
if (qView && ['featured', 'countries', 'favorites', 'custom'].includes(qView)) {
merged.view = qView;
}
const qCountry = url.searchParams.get('country');
if (qCountry !== null) merged.country = qCountry;
const qSearch = url.searchParams.get('q');
if (qSearch !== null) merged.query = qSearch;
return merged;
}
export async function syncStateToUrlAndStorage(state: RadioPersistedState): Promise<string> {
saveLocalState(state);
if (typeof window === 'undefined') return '';
const url = new URL(window.location.href);
if (state.view !== 'featured') url.searchParams.set('view', state.view);
else url.searchParams.delete('view');
if (state.country) url.searchParams.set('country', state.country);
else url.searchParams.delete('country');
if (state.query.trim()) url.searchParams.set('q', state.query.trim());
else url.searchParams.delete('q');
const compactPayload: Partial<RadioPersistedState> = {
view: state.view,
country: state.country,
query: state.query,
playingId: state.playingId,
};
if (state.favorites.length > 0) compactPayload.favorites = state.favorites.slice(0, 30);
if (state.customStations.length > 0) compactPayload.customStations = state.customStations.slice(0, 30);
if (state.listUrls.length > 0) compactPayload.listUrls = state.listUrls.slice(0, 10);
const hasRichState =
Boolean(state.playingId) ||
state.favorites.length > 0 ||
state.customStations.length > 0 ||
state.listUrls.length > 0;
if (hasRichState) {
try {
const token = await compressString(JSON.stringify(compactPayload));
url.hash = `s=${token}`;
} catch {
// Fallback without hash compression
}
} else if (url.hash.startsWith('#s=')) {
url.hash = '';
}
const nextUrl = `${url.pathname}${url.search}${url.hash}`;
window.history.replaceState(null, '', nextUrl);
return url.toString();
}import type { RadioStation } from './types';
export type PlayerStatus = 'idle' | 'buffering' | 'playing' | 'paused' | 'error';
export interface PlayerCallbacks {
onStatusChange: (status: PlayerStatus, station: RadioStation | null, errorMsg?: string) => void;
}
export class RadioAudioController {
private audio: HTMLAudioElement;
private hlsInstance: any = null;
private currentStation: RadioStation | null = null;
private callbacks: PlayerCallbacks;
constructor(audio: HTMLAudioElement, callbacks: PlayerCallbacks) {
this.audio = audio;
this.callbacks = callbacks;
this.audio.addEventListener('waiting', () => {
if (this.currentStation) this.callbacks.onStatusChange('buffering', this.currentStation);
});
this.audio.addEventListener('playing', () => {
if (this.currentStation) {
this.callbacks.onStatusChange('playing', this.currentStation);
this.updateMediaSession('playing');
}
});
this.audio.addEventListener('pause', () => {
if (this.currentStation && !this.audio.ended) {
this.callbacks.onStatusChange('paused', this.currentStation);
this.updateMediaSession('paused');
}
});
this.audio.addEventListener('error', () => {
if (this.currentStation) {
this.callbacks.onStatusChange('error', this.currentStation, 'Stream unavailable or blocked');
}
});
}
private destroyHls() {
if (this.hlsInstance) {
try { this.hlsInstance.destroy(); } catch {}
this.hlsInstance = null;
}
}
private updateMediaSession(playbackState: 'playing' | 'paused' | 'none') {
if (!('mediaSession' in navigator) || !this.currentStation) return;
try {
navigator.mediaSession.playbackState = playbackState;
navigator.mediaSession.metadata = new MediaMetadata({
title: this.currentStation.name,
artist: this.currentStation.country || 'World Radio',
album: 'Mograblog World Radio',
artwork: this.currentStation.favicon
? [{ src: this.currentStation.favicon, sizes: '128x128', type: 'image/png' }]
: [],
});
navigator.mediaSession.setActionHandler('play', () => { void this.resume(); });
navigator.mediaSession.setActionHandler('pause', () => { this.pause(); });
navigator.mediaSession.setActionHandler('stop', () => { this.stop(); });
} catch {
// Ignore MediaSession errors on unsupported browsers
}
}
async play(station: RadioStation): Promise<void> {
this.currentStation = station;
this.destroyHls();
this.callbacks.onStatusChange('buffering', station);
const isHls = /\.m3u8(\?|$)/i.test(station.url);
if (isHls && !this.audio.canPlayType('application/vnd.apple.mpegurl')) {
try {
const mod = await import('https://cdn.jsdelivr.net/npm/[email protected]/dist/hls.mjs');
const Hls = mod.default;
if (Hls && Hls.isSupported()) {
this.hlsInstance = new Hls({ enableWorker: true });
this.hlsInstance.loadSource(station.url);
this.hlsInstance.attachMedia(this.audio);
await this.audio.play();
return;
}
} catch {
// Fall through to direct <audio> src attempt
}
}
this.audio.src = station.url;
this.audio.load();
try {
await this.audio.play();
} catch (err) {
const msg = (err as Error)?.name === 'NotAllowedError'
? 'Tap Play to start audio'
: 'Stream unavailable or blocked';
this.callbacks.onStatusChange('error', station, msg);
}
}
async resume(): Promise<void> {
if (!this.currentStation) return;
try {
await this.audio.play();
} catch {
await this.play(this.currentStation);
}
}
pause(): void {
this.audio.pause();
}
stop(): void {
this.destroyHls();
this.audio.pause();
this.audio.removeAttribute('src');
this.currentStation = null;
this.callbacks.onStatusChange('idle', null);
}
setVolume(val: number): void {
this.audio.volume = Math.min(1, Math.max(0, val));
}
setMuted(muted: boolean): void {
this.audio.muted = muted;
}
getStation(): RadioStation | null {
return this.currentStation;
}
}---
// 100% Frontend World Radio Orchestrator (Curated + Radio Browser + Custom Lists + Stateful URL)
import RadioHeader from './radio/RadioHeader.astro';
import RadioPlayerBar from './radio/RadioPlayerBar.astro';
import RadioAddModal from './radio/RadioAddModal.astro';
---
<div id="radio-arena" class="max-w-6xl mx-auto px-3 sm:px-6 space-y-4">
<RadioPlayerBar />
<RadioHeader />
<div class="flex items-center justify-between text-xs text-neutral-500 dark:text-neutral-400 px-1">
<span id="radio-list-summary">Loading stations...</span>
<span id="radio-url-sync-badge" class="font-mono text-[11px] opacity-80">URL synced</span>
</div>
<div id="radio-station-grid" class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3"></div>
<div
id="radio-empty-state"
class="hidden rounded-2xl border border-dashed border-neutral-300 dark:border-neutral-700 p-8 text-center text-sm text-neutral-500 dark:text-neutral-400"
></div>
<RadioAddModal />
</div>
<script>
import type { RadioCountry, RadioPersistedState, RadioStation, RadioViewMode } from '../lib/radio/types';
import { CURATED_STATIONS } from '../lib/radio/curatedStations';
import { fetchCountries, searchStations } from '../lib/radio/radioBrowserApi';
import { createCustomStation, fetchStationListFromUrl, parseStationListText } from '../lib/radio/playlistParser';
import { DEFAULT_RADIO_STATE, loadInitialState, syncStateToUrlAndStorage } from '../lib/radio/stateStorage';
import { RadioAudioController, type PlayerStatus } from '../lib/radio/audioPlayer';
const arenaEl = document.getElementById('radio-arena');
if (arenaEl) {
let state: RadioPersistedState = { ...DEFAULT_RADIO_STATE };
let directoryStations: RadioStation[] = [];
let countries: RadioCountry[] = [];
let countriesLoaded = false;
let isLoadingDirectory = false;
let directoryError = '';
let searchDebounce: number | null = null;
let directoryAbort: AbortController | null = null;
let currentStatus: PlayerStatus = 'idle';
const gridEl = document.getElementById('radio-station-grid')!;
const emptyEl = document.getElementById('radio-empty-state')!;
const summaryEl = document.getElementById('radio-list-summary')!;
const favCountEl = document.getElementById('radio-fav-count')!;
const customCountEl = document.getElementById('radio-custom-count')!;
const searchInput = document.getElementById('radio-search-input') as HTMLInputElement;
const countrySelect = document.getElementById('radio-country-select') as HTMLSelectElement;
const copyLinkBtn = document.getElementById('radio-copy-link-btn')!;
const copyLinkLabel = document.getElementById('radio-copy-link-label')!;
// Player Bar Elements
const audioEl = document.getElementById('radio-audio-el') as HTMLAudioElement;
const nowDot = document.getElementById('radio-now-dot')!;
const nowName = document.getElementById('radio-now-name')!;
const nowMeta = document.getElementById('radio-now-meta')!;
const nowArt = document.getElementById('radio-now-art')!;
const playPauseBtn = document.getElementById('radio-play-pause-btn') as HTMLButtonElement;
const nowFavBtn = document.getElementById('radio-now-fav-btn') as HTMLButtonElement;
const muteBtn = document.getElementById('radio-mute-btn') as HTMLButtonElement;
const volumeSlider = document.getElementById('radio-volume-slider') as HTMLInputElement;
// Modal Elements
const modalEl = document.getElementById('radio-add-modal')!;
const openAddBtn = document.getElementById('radio-open-add-btn')!;
const closeAddBtn = document.getElementById('radio-add-close-btn')!;
const stationForm = document.getElementById('radio-add-station-form') as HTMLFormElement;
const listForm = document.getElementById('radio-import-list-form') as HTMLFormElement;
const addFeedback = document.getElementById('radio-add-feedback')!;
const escapeHtml = (str: string) =>
(str || '').replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
const isFavorite = (id: string) => state.favorites.some((f) => f.id === id);
const findStationById = (id: string | null): RadioStation | null => {
if (!id) return null;
return (
state.favorites.find((s) => s.id === id) ||
state.customStations.find((s) => s.id === id) ||
CURATED_STATIONS.find((s) => s.id === id) ||
directoryStations.find((s) => s.id === id) ||
null
);
};
const updatePlayerBar = (status: PlayerStatus, station: RadioStation | null, errorMsg?: string) => {
currentStatus = status;
if (!station) {
nowDot.className = 'h-2 w-2 rounded-full bg-neutral-400 flex-shrink-0';
nowName.textContent = 'Pick a station below to listen';
nowMeta.textContent = '100% frontend audio · zero tracking · Media Session ready';
nowArt.textContent = '📻';
playPauseBtn.disabled = true;
playPauseBtn.textContent = 'Play';
nowFavBtn.disabled = true;
return;
}
playPauseBtn.disabled = false;
nowFavBtn.disabled = false;
nowFavBtn.textContent = isFavorite(station.id) ? '★' : '☆';
nowName.textContent = station.name;
if (station.favicon) {
nowArt.innerHTML = `<img src="${escapeHtml(station.favicon)}" alt="" class="w-full h-full object-cover" onerror="this.parentElement.textContent='📻'" />`;
} else {
nowArt.textContent = '📻';
}
const metaParts = [station.country || 'World', station.codec, station.bitrate ? `${station.bitrate}k` : '']
.filter(Boolean)
.join(' · ');
if (status === 'playing') {
nowDot.className = 'h-2 w-2 rounded-full bg-emerald-500 animate-pulse flex-shrink-0';
nowMeta.textContent = `Live · ${metaParts}`;
playPauseBtn.textContent = 'Pause';
} else if (status === 'buffering') {
nowDot.className = 'h-2 w-2 rounded-full bg-amber-500 animate-pulse flex-shrink-0';
nowMeta.textContent = `Buffering · ${metaParts}`;
playPauseBtn.textContent = 'Pause';
} else if (status === 'error') {
nowDot.className = 'h-2 w-2 rounded-full bg-rose-500 flex-shrink-0';
nowMeta.textContent = errorMsg || 'Stream unavailable';
playPauseBtn.textContent = 'Retry';
} else {
nowDot.className = 'h-2 w-2 rounded-full bg-indigo-500 flex-shrink-0';
nowMeta.textContent = `Ready · ${metaParts}`;
playPauseBtn.textContent = 'Play';
}
};
const player = new RadioAudioController(audioEl, {
onStatusChange: (status, station, errorMsg) => {
updatePlayerBar(status, station, errorMsg);
renderStations();
},
});
player.setVolume(Number(volumeSlider.value) / 100);
const persistState = async () => {
favCountEl.textContent = String(state.favorites.length);
customCountEl.textContent = String(state.customStations.length);
await syncStateToUrlAndStorage(state);
};
const toggleFavorite = async (station: RadioStation) => {
if (isFavorite(station.id)) {
state.favorites = state.favorites.filter((s) => s.id !== station.id);
} else {
state.favorites = [station, ...state.favorites];
}
await persistState();
updatePlayerBar(currentStatus, player.getStation() || findStationById(state.playingId));
renderStations();
};
const playStation = async (station: RadioStation) => {
state.playingId = station.id;
await persistState();
await player.play(station);
};
const renderTabs = () => {
document.querySelectorAll<HTMLButtonElement>('.radio-tab-btn').forEach((btn) => {
const active = btn.dataset.radioView === state.view;
btn.className = active
? 'radio-tab-btn px-3 py-1.5 rounded-lg text-xs font-semibold transition cursor-pointer bg-indigo-600 text-white'
: 'radio-tab-btn px-3 py-1.5 rounded-lg text-xs font-semibold transition cursor-pointer border border-neutral-300 dark:border-neutral-700 text-neutral-700 dark:text-neutral-200 hover:bg-neutral-100 dark:hover:bg-neutral-800';
});
};
const getVisibleStations = (): RadioStation[] => {
const q = state.query.trim().toLowerCase();
const filterFn = (list: RadioStation[]) => {
return list.filter((s) => {
if (state.country && state.view !== 'countries') {
if (s.countryCode && s.countryCode !== state.country) return false;
}
if (!q) return true;
return (
s.name.toLowerCase().includes(q) ||
s.country.toLowerCase().includes(q) ||
s.tags.some((t) => t.toLowerCase().includes(q))
);
});
};
if (state.view === 'featured') return filterFn(CURATED_STATIONS);
if (state.view === 'favorites') return filterFn(state.favorites);
if (state.view === 'custom') return filterFn(state.customStations);
return directoryStations;
};
const renderStations = () => {
const stations = getVisibleStations();
const activeId = player.getStation()?.id || state.playingId;
if (state.view === 'countries' && isLoadingDirectory) {
summaryEl.textContent = 'Querying Radio Browser directory...';
gridEl.innerHTML = '';
emptyEl.classList.remove('hidden');
emptyEl.textContent = 'Loading HTTPS stations...';
return;
}
if (state.view === 'countries' && directoryError) {
summaryEl.textContent = 'Directory unavailable';
gridEl.innerHTML = '';
emptyEl.classList.remove('hidden');
emptyEl.textContent = directoryError;
return;
}
summaryEl.textContent = `${stations.length} ${stations.length === 1 ? 'station' : 'stations'} shown`;
if (stations.length === 0) {
gridEl.innerHTML = '';
emptyEl.classList.remove('hidden');
emptyEl.textContent =
state.view === 'favorites'
? 'No favorites yet. Click the star on any station to save it to your browser.'
: state.view === 'custom'
? 'No custom stations yet. Click "+ Add URL / List" to add a stream or M3U/JSON list.'
: 'No matching HTTPS stations found. Try another search or country.';
return;
}
emptyEl.classList.add('hidden');
gridEl.innerHTML = stations
.map((s) => {
const isActive = activeId === s.id;
const isPlaying = isActive && currentStatus === 'playing';
const fav = isFavorite(s.id);
const tagsHtml = s.tags
.slice(0, 3)
.map(
(t) =>
`<span class="px-1.5 py-0.5 rounded bg-neutral-100 dark:bg-neutral-800 text-[10px] text-neutral-600 dark:text-neutral-300">${escapeHtml(t)}</span>`,
)
.join('');
return `
<div class="rounded-2xl border ${
isActive
? 'border-indigo-500 ring-1 ring-indigo-500/40 bg-indigo-50/40 dark:bg-indigo-950/20'
: 'border-neutral-200 dark:border-neutral-800 bg-white dark:bg-neutral-900/60 hover:border-neutral-300 dark:hover:border-neutral-700'
} p-3.5 flex flex-col justify-between gap-3 transition">
<div class="flex items-start justify-between gap-2">
<div class="min-w-0">
<div class="text-sm font-bold text-neutral-900 dark:text-white truncate">${escapeHtml(s.name)}</div>
<div class="text-xs text-neutral-500 dark:text-neutral-400 truncate mt-0.5">
${escapeHtml(s.country || 'World')}${s.codec ? ` · ${escapeHtml(s.codec)}` : ''}
</div>
</div>
<button
type="button"
data-fav-id="${escapeHtml(s.id)}"
title="${fav ? 'Remove from favorites' : 'Save to favorites'}"
class="radio-fav-btn flex-shrink-0 rounded-lg px-2 py-1 text-sm ${
fav ? 'text-amber-500' : 'text-neutral-400 hover:text-amber-500'
} cursor-pointer"
>
${fav ? '★' : '☆'}
</button>
</div>
<div class="flex items-center justify-between gap-2">
<div class="flex flex-wrap gap-1 min-w-0">${tagsHtml}</div>
<button
type="button"
data-play-id="${escapeHtml(s.id)}"
class="radio-play-btn flex-shrink-0 rounded-xl px-3 py-1.5 text-xs font-semibold transition cursor-pointer ${
isPlaying
? 'bg-emerald-600 text-white'
: 'bg-indigo-600 hover:bg-indigo-500 text-white'
}"
>
${isPlaying ? 'Playing' : isActive && currentStatus === 'buffering' ? 'Loading…' : 'Play'}
</button>
</div>
</div>
`;
})
.join('');
};
const loadDirectory = async () => {
if (directoryAbort) directoryAbort.abort();
directoryAbort = new AbortController();
isLoadingDirectory = true;
directoryError = '';
renderStations();
try {
if (!countriesLoaded) {
countries = await fetchCountries(directoryAbort.signal);
countriesLoaded = true;
const prev = state.country;
countrySelect.innerHTML =
'<option value="">All Countries (Top Voted)</option>' +
countries
.slice(0, 120)
.map((c) => `<option value="${escapeHtml(c.code)}">${escapeHtml(c.name)} (${c.stationCount})</option>`)
.join('');
countrySelect.value = prev;
}
directoryStations = await searchStations(
{ countryCode: state.country || undefined, query: state.query || undefined, limit: 60 },
directoryAbort.signal,
);
} catch (err) {
if ((err as Error)?.name === 'AbortError') return;
directoryError = 'Could not reach Radio Browser mirrors. Try again or use Featured / Custom stations.';
} finally {
isLoadingDirectory = false;
renderStations();
}
};
const switchView = async (view: RadioViewMode) => {
state.view = view;
renderTabs();
await persistState();
if (view === 'countries') {
await loadDirectory();
} else {
renderStations();
}
};
// Event Delegation for Station Cards
gridEl.addEventListener('click', (e) => {
const target = e.target as HTMLElement;
const playBtn = target.closest<HTMLButtonElement>('.radio-play-btn');
if (playBtn?.dataset.playId) {
const station = getVisibleStations().find((s) => s.id === playBtn.dataset.playId);
if (station) void playStation(station);
return;
}
const favBtn = target.closest<HTMLButtonElement>('.radio-fav-btn');
if (favBtn?.dataset.favId) {
const station = getVisibleStations().find((s) => s.id === favBtn.dataset.favId);
if (station) void toggleFavorite(station);
}
});
document.querySelectorAll<HTMLButtonElement>('.radio-tab-btn').forEach((btn) => {
btn.addEventListener('click', () => {
const view = btn.dataset.radioView as RadioViewMode | undefined;
if (view) void switchView(view);
});
});
searchInput.addEventListener('input', () => {
state.query = searchInput.value;
if (searchDebounce) window.clearTimeout(searchDebounce);
searchDebounce = window.setTimeout(() => {
void persistState();
if (state.view === 'countries') void loadDirectory();
else renderStations();
}, 250);
});
countrySelect.addEventListener('change', () => {
state.country = countrySelect.value;
if (state.country && state.view === 'featured') {
state.view = 'countries';
renderTabs();
}
void persistState();
if (state.view === 'countries') void loadDirectory();
else renderStations();
});
playPauseBtn.addEventListener('click', () => {
if (currentStatus === 'playing' || currentStatus === 'buffering') {
player.pause();
} else {
const target = player.getStation() || findStationById(state.playingId);
if (target) void player.play(target);
}
});
nowFavBtn.addEventListener('click', () => {
const active = player.getStation() || findStationById(state.playingId);
if (active) void toggleFavorite(active);
});
volumeSlider.addEventListener('input', () => {
const vol = Number(volumeSlider.value) / 100;
player.setVolume(vol);
player.setMuted(vol === 0);
muteBtn.textContent = vol === 0 ? '🔇' : '🔊';
});
muteBtn.addEventListener('click', () => {
const nextMuted = !audioEl.muted;
player.setMuted(nextMuted);
muteBtn.textContent = nextMuted ? '🔇' : '🔊';
});
copyLinkBtn.addEventListener('click', async () => {
const fullUrl = await syncStateToUrlAndStorage(state);
try {
await navigator.clipboard.writeText(fullUrl || window.location.href);
copyLinkLabel.textContent = 'Copied!';
window.setTimeout(() => {
copyLinkLabel.textContent = 'Copy Stateful URL';
}, 1800);
} catch {}
});
// Modal Controls
const setAddFeedback = (msg: string, isError = false) => {
addFeedback.textContent = msg;
addFeedback.className = isError
? 'text-xs rounded-lg px-3 py-2 bg-rose-500/10 text-rose-500 border border-rose-500/20'
: 'text-xs rounded-lg px-3 py-2 bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 border border-emerald-500/20';
addFeedback.classList.remove('hidden');
};
openAddBtn.addEventListener('click', () => {
addFeedback.classList.add('hidden');
modalEl.classList.remove('hidden');
});
closeAddBtn.addEventListener('click', () => modalEl.classList.add('hidden'));
modalEl.addEventListener('click', (e) => {
if (e.target === modalEl) modalEl.classList.add('hidden');
});
document.querySelectorAll<HTMLButtonElement>('.radio-add-mode-btn').forEach((btn) => {
btn.addEventListener('click', () => {
const mode = btn.dataset.addMode;
stationForm.classList.toggle('hidden', mode !== 'station');
listForm.classList.toggle('hidden', mode !== 'list');
document.querySelectorAll<HTMLButtonElement>('.radio-add-mode-btn').forEach((b) => {
const active = b.dataset.addMode === mode;
b.className = active
? 'radio-add-mode-btn px-3 py-1.5 rounded-lg text-xs font-semibold bg-indigo-600 text-white cursor-pointer'
: 'radio-add-mode-btn px-3 py-1.5 rounded-lg text-xs font-semibold border border-neutral-300 dark:border-neutral-700 text-neutral-700 dark:text-neutral-200 cursor-pointer';
});
});
});
const mergeCustomStations = async (incoming: RadioStation[]) => {
const byId = new Map(state.customStations.map((s) => [s.id, s]));
incoming.forEach((s) => byId.set(s.id, s));
state.customStations = Array.from(byId.values());
state.view = 'custom';
renderTabs();
await persistState();
renderStations();
};
stationForm.addEventListener('submit', async (e) => {
e.preventDefault();
const url = (document.getElementById('radio-input-url') as HTMLInputElement).value;
const name = (document.getElementById('radio-input-name') as HTMLInputElement).value;
const country = (document.getElementById('radio-input-country') as HTMLInputElement).value;
const station = createCustomStation({ url, name, country });
if (!station) {
setAddFeedback('Please enter a valid https:// stream URL.', true);
return;
}
await mergeCustomStations([station]);
stationForm.reset();
modalEl.classList.add('hidden');
void playStation(station);
});
listForm.addEventListener('submit', async (e) => {
e.preventDefault();
const listUrl = (document.getElementById('radio-input-list-url') as HTMLInputElement).value.trim();
const rawText = (document.getElementById('radio-input-list-raw') as HTMLTextAreaElement).value.trim();
try {
let imported: RadioStation[] = [];
if (listUrl) {
imported = await fetchStationListFromUrl(listUrl);
state.listUrls = Array.from(new Set([listUrl, ...state.listUrls]));
} else if (rawText) {
imported = parseStationListText(rawText);
} else {
setAddFeedback('Enter a list URL or paste M3U/JSON/PLS text.', true);
return;
}
if (imported.length === 0) {
setAddFeedback('No valid https:// streams found.', true);
return;
}
await mergeCustomStations(imported);
listForm.reset();
setAddFeedback(`Imported ${imported.length} station(s)!`);
window.setTimeout(() => modalEl.classList.add('hidden'), 600);
} catch (err) {
setAddFeedback((err as Error)?.message || 'Failed to import list (check CORS or format).', true);
}
});
// Boot: restore state from URL hash / query + localStorage
(async () => {
state = await loadInitialState();
searchInput.value = state.query;
favCountEl.textContent = String(state.favorites.length);
customCountEl.textContent = String(state.customStations.length);
renderTabs();
// Preload countries dropdown in background
fetchCountries()
.then((list) => {
countries = list;
countriesLoaded = true;
countrySelect.innerHTML =
'<option value="">All Countries (Top Voted)</option>' +
countries
.slice(0, 120)
.map((c) => `<option value="${escapeHtml(c.code)}">${escapeHtml(c.name)} (${c.stationCount})</option>`)
.join('');
countrySelect.value = state.country;
})
.catch(() => {});
const restoredStation = findStationById(state.playingId);
if (restoredStation) {
updatePlayerBar('idle', restoredStation);
}
if (state.view === 'countries') {
await loadDirectory();
} else {
renderStations();
}
})();
}
</script>---
// World Radio Header: View tabs, search, country filter, add station/list, stateful link copy
---
<div class="rounded-2xl border border-neutral-200 dark:border-neutral-800 bg-neutral-50/80 dark:bg-neutral-900/70 p-3.5 sm:p-4 space-y-3">
<div class="flex flex-wrap items-center justify-between gap-2.5">
<!-- View Mode Tabs -->
<div id="radio-view-tabs" class="flex flex-wrap items-center gap-1.5" role="tablist" aria-label="Radio Views">
<button
type="button"
data-radio-view="featured"
class="radio-tab-btn px-3 py-1.5 rounded-lg text-xs font-semibold transition cursor-pointer bg-indigo-600 text-white"
>
Featured
</button>
<button
type="button"
data-radio-view="countries"
class="radio-tab-btn px-3 py-1.5 rounded-lg text-xs font-semibold transition cursor-pointer border border-neutral-300 dark:border-neutral-700 text-neutral-700 dark:text-neutral-200 hover:bg-neutral-100 dark:hover:bg-neutral-800"
>
World Directory
</button>
<button
type="button"
data-radio-view="favorites"
class="radio-tab-btn px-3 py-1.5 rounded-lg text-xs font-semibold transition cursor-pointer border border-neutral-300 dark:border-neutral-700 text-neutral-700 dark:text-neutral-200 hover:bg-neutral-100 dark:hover:bg-neutral-800"
>
Favorites <span id="radio-fav-count" class="ml-1 opacity-75">0</span>
</button>
<button
type="button"
data-radio-view="custom"
class="radio-tab-btn px-3 py-1.5 rounded-lg text-xs font-semibold transition cursor-pointer border border-neutral-300 dark:border-neutral-700 text-neutral-700 dark:text-neutral-200 hover:bg-neutral-100 dark:hover:bg-neutral-800"
>
Custom <span id="radio-custom-count" class="ml-1 opacity-75">0</span>
</button>
</div>
<!-- Actions -->
<div class="flex flex-wrap items-center gap-2">
<button
id="radio-open-add-btn"
type="button"
class="inline-flex items-center gap-1.5 rounded-lg bg-indigo-600 hover:bg-indigo-500 px-3 py-1.5 text-xs font-semibold text-white transition cursor-pointer"
>
<span>+ Add URL / List</span>
</button>
<button
id="radio-copy-link-btn"
type="button"
title="Copy bookmarkable URL with your current filters, favorites, and custom stations"
class="inline-flex items-center gap-1.5 rounded-lg border border-neutral-300 dark:border-neutral-700 bg-white dark:bg-neutral-800 px-3 py-1.5 text-xs font-medium text-neutral-700 dark:text-neutral-200 hover:border-indigo-500 transition cursor-pointer"
>
<span id="radio-copy-link-label">Copy Stateful URL</span>
</button>
</div>
</div>
<!-- Search & Country Filter -->
<div class="grid grid-cols-1 sm:grid-cols-12 gap-2.5">
<div class="sm:col-span-7 relative">
<input
id="radio-search-input"
type="search"
placeholder="Search stations, genres, or cities..."
class="w-full rounded-xl border border-neutral-300 dark:border-neutral-700 bg-white dark:bg-neutral-950 px-3.5 py-2 text-xs sm:text-sm text-neutral-900 dark:text-neutral-100 placeholder:text-neutral-400 focus:outline-none focus:ring-2 focus:ring-indigo-500"
/>
</div>
<div class="sm:col-span-5">
<select
id="radio-country-select"
aria-label="Filter by country"
class="w-full rounded-xl border border-neutral-300 dark:border-neutral-700 bg-white dark:bg-neutral-950 px-3 py-2 text-xs sm:text-sm text-neutral-900 dark:text-neutral-100 focus:outline-none focus:ring-2 focus:ring-indigo-500"
>
<option value="">All Countries (Top Voted)</option>
</select>
</div>
</div>
</div>---
// Sticky Now-Playing Bar with playback controls, volume, favorite toggle, and MediaSession integration
---
<div
id="radio-player-bar"
class="rounded-2xl border border-neutral-200 dark:border-neutral-800 bg-white/95 dark:bg-neutral-900/95 backdrop-blur px-4 py-3 shadow-sm flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3"
>
<div class="flex items-center gap-3 min-w-0 flex-1">
<div
id="radio-now-art"
class="w-10 h-10 rounded-xl bg-indigo-500/10 border border-indigo-500/20 flex items-center justify-center text-lg flex-shrink-0 overflow-hidden"
>
📻
</div>
<div class="min-w-0 flex-1">
<div class="flex items-center gap-2">
<span id="radio-now-dot" class="h-2 w-2 rounded-full bg-neutral-400 flex-shrink-0"></span>
<span id="radio-now-name" class="text-sm font-bold text-neutral-900 dark:text-white truncate">
Pick a station below to listen
</span>
</div>
<div id="radio-now-meta" class="text-xs text-neutral-500 dark:text-neutral-400 truncate mt-0.5">
100% frontend audio · zero tracking · Media Session ready
</div>
</div>
</div>
<div class="flex items-center gap-2.5 w-full sm:w-auto justify-between sm:justify-end">
<div class="flex items-center gap-1.5">
<button
id="radio-mute-btn"
type="button"
title="Mute / Unmute"
class="rounded-lg border border-neutral-300 dark:border-neutral-700 bg-neutral-50 dark:bg-neutral-800 px-2.5 py-1.5 text-xs text-neutral-700 dark:text-neutral-200 hover:border-indigo-500 transition cursor-pointer"
>
🔊
</button>
<input
id="radio-volume-slider"
type="range"
min="0"
max="100"
value="85"
aria-label="Volume"
class="w-20 sm:w-24 accent-indigo-600 cursor-pointer"
/>
</div>
<div class="flex items-center gap-2">
<button
id="radio-now-fav-btn"
type="button"
disabled
title="Favorite current station"
class="rounded-lg border border-neutral-300 dark:border-neutral-700 bg-neutral-50 dark:bg-neutral-800 px-2.5 py-1.5 text-xs font-semibold text-neutral-600 dark:text-neutral-300 disabled:opacity-40 hover:border-amber-500 transition cursor-pointer"
>
☆
</button>
<button
id="radio-play-pause-btn"
type="button"
disabled
class="rounded-xl bg-indigo-600 hover:bg-indigo-500 disabled:opacity-40 px-4 py-1.5 text-xs font-bold text-white transition cursor-pointer min-w-[78px]"
>
Play
</button>
</div>
</div>
<audio id="radio-audio-el" preload="none"></audio>
</div>---
// Modal to add a direct HTTPS stream URL or import an external JSON/M3U/PLS station list
---
<div
id="radio-add-modal"
class="hidden fixed inset-0 z-50 bg-black/60 backdrop-blur-sm p-4 flex items-center justify-center"
role="dialog"
aria-modal="true"
aria-labelledby="radio-add-title"
>
<div class="w-full max-w-lg rounded-2xl border border-neutral-200 dark:border-neutral-800 bg-white dark:bg-neutral-900 p-5 shadow-2xl space-y-4">
<div class="flex items-center justify-between">
<h3 id="radio-add-title" class="text-base font-bold text-neutral-900 dark:text-white">
Add Station or Import List
</h3>
<button
id="radio-add-close-btn"
type="button"
class="rounded-lg px-2 py-1 text-xs font-semibold text-neutral-500 hover:text-neutral-900 dark:hover:text-white cursor-pointer"
>
✕ Close
</button>
</div>
<div class="flex gap-2 border-b border-neutral-200 dark:border-neutral-800 pb-2.5">
<button
type="button"
data-add-mode="station"
class="radio-add-mode-btn px-3 py-1.5 rounded-lg text-xs font-semibold bg-indigo-600 text-white cursor-pointer"
>
Single Stream URL
</button>
<button
type="button"
data-add-mode="list"
class="radio-add-mode-btn px-3 py-1.5 rounded-lg text-xs font-semibold border border-neutral-300 dark:border-neutral-700 text-neutral-700 dark:text-neutral-200 cursor-pointer"
>
Import List URL / M3U
</button>
</div>
<!-- Single Station Form -->
<form id="radio-add-station-form" class="space-y-3">
<div>
<label class="block text-xs font-medium text-neutral-600 dark:text-neutral-300 mb-1">
Stream URL (HTTPS required)
</label>
<input
id="radio-input-url"
type="url"
required
placeholder="https://ice1.somafm.com/groovesalad-128-mp3"
class="w-full rounded-xl border border-neutral-300 dark:border-neutral-700 bg-neutral-50 dark:bg-neutral-950 px-3 py-2 text-xs text-neutral-900 dark:text-neutral-100"
/>
</div>
<div class="grid grid-cols-1 sm:grid-cols-2 gap-2.5">
<div>
<label class="block text-xs font-medium text-neutral-600 dark:text-neutral-300 mb-1">
Station Name
</label>
<input
id="radio-input-name"
type="text"
placeholder="My Favorite FM"
class="w-full rounded-xl border border-neutral-300 dark:border-neutral-700 bg-neutral-50 dark:bg-neutral-950 px-3 py-2 text-xs text-neutral-900 dark:text-neutral-100"
/>
</div>
<div>
<label class="block text-xs font-medium text-neutral-600 dark:text-neutral-300 mb-1">
Country / Genre
</label>
<input
id="radio-input-country"
type="text"
placeholder="Japan · Jazz"
class="w-full rounded-xl border border-neutral-300 dark:border-neutral-700 bg-neutral-50 dark:bg-neutral-950 px-3 py-2 text-xs text-neutral-900 dark:text-neutral-100"
/>
</div>
</div>
<button
type="submit"
class="w-full rounded-xl bg-indigo-600 hover:bg-indigo-500 py-2 text-xs font-bold text-white transition cursor-pointer"
>
Add & Save to Browser
</button>
</form>
<!-- Import List Form -->
<form id="radio-import-list-form" class="hidden space-y-3">
<div>
<label class="block text-xs font-medium text-neutral-600 dark:text-neutral-300 mb-1">
Playlist URL (.json, .m3u, .pls — CORS-enabled hosts like GitHub Raw)
</label>
<input
id="radio-input-list-url"
type="url"
placeholder="https://niftyopen.github.io/OpenStations/stations.json"
class="w-full rounded-xl border border-neutral-300 dark:border-neutral-700 bg-neutral-50 dark:bg-neutral-950 px-3 py-2 text-xs text-neutral-900 dark:text-neutral-100"
/>
</div>
<div>
<label class="block text-xs font-medium text-neutral-600 dark:text-neutral-300 mb-1">
Or Paste Raw M3U / JSON / PLS Text (bypasses CORS)
</label>
<textarea
id="radio-input-list-raw"
rows="4"
placeholder="#EXTM3U #EXTINF:-1,Example Station https://stream.example.com/live.mp3"
class="w-full rounded-xl border border-neutral-300 dark:border-neutral-700 bg-neutral-50 dark:bg-neutral-950 px-3 py-2 text-xs font-mono text-neutral-900 dark:text-neutral-100"
></textarea>
</div>
<button
type="submit"
class="w-full rounded-xl bg-indigo-600 hover:bg-indigo-500 py-2 text-xs font-bold text-white transition cursor-pointer"
>
Import Stations
</button>
</form>
<div id="radio-add-feedback" class="hidden text-xs rounded-lg px-3 py-2"></div>
</div>
</div>