Islamic_clock / background_audio.js1
Asem75's picture
Rename background_audio.js to background_audio.js1
f777c76 verified
Raw History Blame Contribute Delete
5.43 kB
/* طبقة عامة للصوت في الخلفية: الراديو والقرآن وأي <audio>.
1) تعريف الجلسة (Media Session) ليتعامل معها الهاتف كتشغيل وسائط ويعرض التحكم على شاشة القفل.
2) إن أوقف المتصفح الصوت لحظة إخفاء الصفحة (لا المستخدم ولا كود التطبيق) يُستأنف مرة واحدة.
يجب تحميله قبل بقية السكربتات. للوحدات الأخرى: MuslimBackgroundAudio.describe(audioElement,{title,artist}) */
(function () {
'use strict';
const session = navigator.mediaSession, tracked = new WeakSet(), intentional = new WeakSet(), info = new WeakMap();
const nativePlay = HTMLMediaElement.prototype.play, nativePause = HTMLMediaElement.prototype.pause;
let current = null, hiddenAt = -Infinity;
// سجل تشخيصي يبقى في الجهاز: افتح الصفحة بـ #audiolog لعرضه، و#audiolog-clear لمسحه.
const LOG_KEY = 'bg_audio_log', LOG_MAX = 90;
const where = (stack) => String(stack || '').split('\n').slice(2, 6).map((l) => l.trim().replace(/^at /, '').replace(/https?:\/\/[^/]+\//, '').replace(/\?v=[^:]*/, '')).join(' < ');
function log(kind, extra) {
try {
const list = JSON.parse(localStorage.getItem(LOG_KEY) || '[]');
list.push(Object.assign({ t: new Date().toISOString().slice(11, 23), v: document.visibilityState, k: kind }, extra));
localStorage.setItem(LOG_KEY, JSON.stringify(list.slice(-LOG_MAX)));
} catch (_) {}
}
const state = (el) => ({ rs: el.readyState, ns: el.networkState, host: String(el.currentSrc || el.src || '').replace(/^https?:\/\//, '').split('/')[0] });
const RESUME_WINDOW_MS = 2000; // الإيقاف الذي يلي الإخفاء مباشرة فقط يُعدّ إيقافًا من المتصفح
const RESUME_DELAY_MS = 300;
function publish(el) {
if (!session || typeof MediaMetadata === 'undefined') return;
const d = info.get(el) || {};
session.metadata = new MediaMetadata({
title: d.title || el.dataset.title || el.getAttribute('aria-label') || el.title || document.title || '',
artist: d.artist || el.dataset.artist || '', album: d.album || '', artwork: d.artwork || []
});
}
function track(el) {
if (tracked.has(el)) return;
tracked.add(el);
for (const type of ['waiting', 'stalled', 'suspend', 'emptied', 'abort', 'ended']) el.addEventListener(type, () => log(type, state(el)));
el.addEventListener('error', () => log('error', Object.assign({ code: el.error && el.error.code }, state(el))));
el.addEventListener('playing', () => { log('playing', state(el)); current = el; intentional.delete(el); publish(el); if (session) session.playbackState = 'playing'; });
el.addEventListener('pause', () => {
log('pause-event', state(el));
if (current !== el) return;
if (session) session.playbackState = 'paused';
const justHidden = document.hidden && performance.now() - hiddenAt < RESUME_WINDOW_MS;
if (justHidden && !el.ended && !intentional.has(el)) setTimeout(() => { if (el.paused && !el.ended) nativePlay.call(el).catch(() => {}); }, RESUME_DELAY_MS);
});
el.addEventListener('ended', () => { if (current === el && session) session.playbackState = 'none'; });
}
HTMLMediaElement.prototype.play = function () { track(this); log('play-call', { by: where(new Error().stack) }); return nativePlay.apply(this, arguments); };
HTMLMediaElement.prototype.pause = function () { intentional.add(this); log('PAUSE-CALL-BY-CODE', { by: where(new Error().stack) }); return nativePause.apply(this, arguments); };
document.addEventListener('visibilitychange', () => { if (document.hidden) hiddenAt = performance.now(); log('visibility'); });
for (const type of ['freeze', 'resume']) document.addEventListener(type, () => log('lifecycle-' + type));
window.addEventListener('pagehide', () => log('pagehide'));
function showLog() {
if (location.hash === '#audiolog-clear') { try { localStorage.removeItem(LOG_KEY); } catch (_) {} return; }
if (location.hash !== '#audiolog' || document.getElementById('audioLog')) return;
let rows = []; try { rows = JSON.parse(localStorage.getItem(LOG_KEY) || '[]'); } catch (_) {}
const box = document.createElement('pre'); box.id = 'audioLog';
box.style.cssText = 'margin:12px;padding:12px;border-radius:12px;background:#10212b;color:#fff;font:11px/1.55 monospace;white-space:pre-wrap;direction:ltr;position:relative;z-index:99999';
box.textContent = rows.map((r) => Object.keys(r).map((k) => k + '=' + r[k]).join(' ')).join('\n') || 'empty';
document.body.appendChild(box);
}
document.addEventListener('DOMContentLoaded', showLog); window.addEventListener('hashchange', showLog);
if (session) {
const set = (action, fn) => { try { session.setActionHandler(action, fn); } catch (_) {} };
set('play', () => { if (current) { intentional.delete(current); nativePlay.call(current).catch(() => {}); } });
set('pause', () => { if (current) { intentional.add(current); nativePause.call(current); } });
set('stop', () => { if (current) { intentional.add(current); nativePause.call(current); current.currentTime = 0; } });
}
window.MuslimBackgroundAudio = Object.freeze({ describe(el, data) { info.set(el, data || {}); if (current === el) publish(el); } });
})();