跳转到内容

MediaWiki:Gadget-AudioText.js:修订间差异

来自电棍ottowiki
 
(未显示同一用户的13个中间版本)
第1行: 第1行:
// MediaWiki:Gadget-AudioText.js
// MediaWiki:Gadget-AudioText.js
(function() {
(function() {
     // 预缓存音频URL(提升隐私模式下的成功率)
     const audioUrlCache = new Map();
    let cachedAudioUrl = null;


     mw.hook('wikipage.content').add(function() {
     // 播放音频核心逻辑
         alert("🎉 JS脚本已加载!"); // 保留初始提示
    function handlePlay(element) {
         const audioFile = element.dataset.audioFile;
          
          
         document.querySelectorAll('.audio-trigger').forEach(element => {
         // 优先使用缓存
             element.addEventListener('click', async function() {
        if (audioUrlCache.has(audioFile)) {
                try {
             new Audio(audioUrlCache.get(audioFile)).play();
                    // 立即尝试播放缓存(减少API请求)
            return;
                    if (cachedAudioUrl) {
        }
                        await playAudio(cachedAudioUrl);
                        return showDebugInfo(element, "✅ 使用缓存播放成功"); // [!code focus]
                    }


                    // 首次加载流程
        // 通过API获取真实URL
                    const audioFile = element.dataset.audioFile;
        const apiUrl = mw.util.wikiScript('api') + '?action=query&titles=' +  
                    const apiUrl = mw.util.wikiScript('api') + '?action=query&titles=' +  
            encodeURIComponent(audioFile) + '&prop=imageinfo&iiprop=url&format=json';
                        encodeURIComponent(audioFile) + '&prop=imageinfo&iiprop=url&format=json';


                    // 并行处理:立即播放 + 后台更新缓存
        fetch(apiUrl)
                    const audioUrl = await fetch(apiUrl)
            .then(response => response.json())
                        .then(response => response.json())
            .then(data => {
                        .then(data => {
                const pages = data.query.pages;
                            const pages = data.query.pages;
                const pageId = Object.keys(pages)[0];
                            const pageId = Object.keys(pages)[0];
                const audioUrl = pages[pageId].imageinfo[0].url;
                            return pages[pageId].imageinfo[0].url;
                audioUrlCache.set(audioFile, audioUrl);
                        });
                 new Audio(audioUrl).play();
                   
                    cachedAudioUrl = audioUrl; // 更新缓存
                   
                    // 立即播放不等待调试提示
                    await playAudio(audioUrl);
                   
                    // 播放成功后显示调试信息
                    showDebugInfo(element, `🎵 音频URL: ${audioUrl}\n✅ 实时播放成功`); // [!code focus]
                   
                 } catch (error) {
                    showDebugInfo(element, `❌ 错误: ${error.message}\n⚠️ 请关闭防跟踪功能后重试`);
                }
             });
             });
         });
    }
    });
 
    // 初始化事件绑定
    function initAudioTriggers() {
         document.querySelectorAll('.audio-trigger').forEach(element => {
            if (element._audioBound) return;
            element._audioBound = true;
 
            // 统一事件处理器(不阻止冒泡和默认行为)
            const handler = (event) => {
                handlePlay(element);
                // 不调用 event.stopPropagation() 或 event.preventDefault()
            };


    // 专用播放函数
            // 同时绑定touch和click(passive模式提升移动端性能)
    async function playAudio(url) {
            element.addEventListener('touchstart', handler, { passive: true });
        const audio = new Audio(url);
            element.addEventListener('click', handler);
        await audio.play().catch(e => {
            throw new Error(`播放被阻止 (${e.message})`);
         });
         });
     }
     }


     // 延迟显示调试信息(不影响播放)
     // 页面加载时初始化
     function showDebugInfo(element, message) { // [!code focus]
     mw.hook('wikipage.content').add(initAudioTriggers);
        setTimeout(() => { // 延迟500ms确保播放已触发
    mw.loader.using('mediawiki.api').then(initAudioTriggers);
            alert(message);
            element.style.backgroundColor = "#f0f8ff"; // 可视化反馈
            setTimeout(() => element.style.backgroundColor = "", 1000);
        }, 500);
    }
})();
})();

2025年5月24日 (六) 23:56的最新版本

// MediaWiki:Gadget-AudioText.js
(function() {
    const audioUrlCache = new Map();

    // 播放音频核心逻辑
    function handlePlay(element) {
        const audioFile = element.dataset.audioFile;
        
        // 优先使用缓存
        if (audioUrlCache.has(audioFile)) {
            new Audio(audioUrlCache.get(audioFile)).play();
            return;
        }

        // 通过API获取真实URL
        const apiUrl = mw.util.wikiScript('api') + '?action=query&titles=' + 
            encodeURIComponent(audioFile) + '&prop=imageinfo&iiprop=url&format=json';

        fetch(apiUrl)
            .then(response => response.json())
            .then(data => {
                const pages = data.query.pages;
                const pageId = Object.keys(pages)[0];
                const audioUrl = pages[pageId].imageinfo[0].url;
                audioUrlCache.set(audioFile, audioUrl);
                new Audio(audioUrl).play();
            });
    }

    // 初始化事件绑定
    function initAudioTriggers() {
        document.querySelectorAll('.audio-trigger').forEach(element => {
            if (element._audioBound) return;
            element._audioBound = true;

            // 统一事件处理器(不阻止冒泡和默认行为)
            const handler = (event) => {
                handlePlay(element);
                // 不调用 event.stopPropagation() 或 event.preventDefault()
            };

            // 同时绑定touch和click(passive模式提升移动端性能)
            element.addEventListener('touchstart', handler, { passive: true });
            element.addEventListener('click', handler);
        });
    }

    // 页面加载时初始化
    mw.hook('wikipage.content').add(initAudioTriggers);
    mw.loader.using('mediawiki.api').then(initAudioTriggers);
})();