跳转到内容

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

来自电棍ottowiki
OctoberSama
OctoberSama留言 | 贡献 (撤销OctoberSama讨论)的修订版本6363
第1行: 第1行:
// MediaWiki:Gadget-AudioText.js
// MediaWiki:Gadget-AudioText.js
(function() {
(function() {
     // 预加载音频URL缓存
     mw.hook('wikipage.content').add(function() {
    const audioUrlCache = new Map();
        alert("🎉 JS脚本已加载!"); // 1. 脚本加载确认


    // 统一处理播放逻辑
        document.querySelectorAll('.audio-trigger').forEach(element => {
    function handlePlay(element) {
            element.addEventListener('click', function() {
        const originalText = element.textContent;
                alert("🖱️ 点击事件已触发!"); // 2. 点击事件确认
       
               
        // 显示加载状态
                const audioFile = element.dataset.audioFile;
        element.textContent = "加载中...";
                alert("📁 音频文件名: " + audioFile); // 3. 显示模板参数
        element.style.color = "#999";


        const audioFile = element.dataset.audioFile;
                // 构造API请求URL
       
                const apiUrl = mw.util.wikiScript('api') + '?action=query&titles=' +
        // 优先使用缓存
                    encodeURIComponent(audioFile) + '&prop=imageinfo&iiprop=url&format=json';
        if (audioUrlCache.has(audioFile)) {
                alert("🔗 即将请求API: \n" + apiUrl); // 4. 显示API地址
            playAudio(audioUrlCache.get(audioFile), element, originalText);
            return;
        }


        // 通过API获取音频真实URL
                // 发送API请求
        const apiUrl = mw.util.wikiScript('api') + '?action=query&titles=' +
                fetch(apiUrl)
            encodeURIComponent(audioFile) + '&prop=imageinfo&iiprop=url&format=json';
                    .then(response => {
                        alert("📡 API响应状态: " + response.status); // 5. HTTP状态码
                        return response.json();
                    })
                    .then(data => {
                        alert("📦 API返回原始数据: \n" + JSON.stringify(data)); // 6. 原始API数据
                       
                        const pages = data.query.pages;
                        const pageId = Object.keys(pages)[0];
                        const audioUrl = pages[pageId].imageinfo[0].url;
                        alert("🎵 解析出的音频URL: \n" + audioUrl); // 7. 最终音频地址


        fetch(apiUrl)
                        // 尝试播放
            .then(response => response.json())
                        const audio = new Audio(audioUrl);
            .then(data => {
                        audio.play()
                const pages = data.query.pages;
                            .then(() => alert("✅ 播放成功!"))
                const pageId = Object.keys(pages)[0];
                            .catch(e => alert("❌ 播放失败: " + e.message)); // 8. 播放结果
                const audioUrl = pages[pageId].imageinfo[0]?.url;
                    })
               
                    .catch(error => {
                if (!audioUrl) {
                        alert("💥 发生严重错误: " + error.message); // 9. 全局错误捕获
                    throw new Error("未找到音频文件");
                    });
                }
               
                // 缓存URL并播放
                audioUrlCache.set(audioFile, audioUrl);
                playAudio(audioUrl, element, originalText);
            })
            .catch(() => {
                // 失败状态提示
                element.textContent = "加载失败,点击重试";
                element.style.color = "red";
             });
             });
    }
    function playAudio(url, element, originalText) {
        const audio = new Audio(url);
       
        audio.play().then(() => {
            // 播放成功恢复状态
            element.textContent = originalText;
            element.style.color = "blue";
        }).catch(() => {
            // 静默失败,不干扰用户
            element.textContent = originalText;
            element.style.color = "blue";
         });
         });
     }
     });
 
    // 事件绑定(支持移动端)
    function initAudioTriggers() {
        document.querySelectorAll('.audio-trigger').forEach(element => {
            if (element._audioBound) return;
            element._audioBound = true;
 
            const handler = (event) => {
                event.preventDefault();
                handlePlay(element);
            };
 
            element.addEventListener('touchstart', handler, { passive: false });
            element.addEventListener('click', handler);
        });
    }
 
    // 初始化
    mw.hook('wikipage.content').add(initAudioTriggers);
    mw.loader.using('mediawiki.api').then(initAudioTriggers);
})();
})();

2025年5月24日 (六) 23:21的版本

// MediaWiki:Gadget-AudioText.js
(function() {
    mw.hook('wikipage.content').add(function() {
        alert("🎉 JS脚本已加载!"); // 1. 脚本加载确认

        document.querySelectorAll('.audio-trigger').forEach(element => {
            element.addEventListener('click', function() {
                alert("🖱️ 点击事件已触发!"); // 2. 点击事件确认
                
                const audioFile = element.dataset.audioFile;
                alert("📁 音频文件名: " + audioFile); // 3. 显示模板参数

                // 构造API请求URL
                const apiUrl = mw.util.wikiScript('api') + '?action=query&titles=' + 
                    encodeURIComponent(audioFile) + '&prop=imageinfo&iiprop=url&format=json';
                alert("🔗 即将请求API: \n" + apiUrl); // 4. 显示API地址

                // 发送API请求
                fetch(apiUrl)
                    .then(response => {
                        alert("📡 API响应状态: " + response.status); // 5. HTTP状态码
                        return response.json();
                    })
                    .then(data => {
                        alert("📦 API返回原始数据: \n" + JSON.stringify(data)); // 6. 原始API数据
                        
                        const pages = data.query.pages;
                        const pageId = Object.keys(pages)[0];
                        const audioUrl = pages[pageId].imageinfo[0].url;
                        alert("🎵 解析出的音频URL: \n" + audioUrl); // 7. 最终音频地址

                        // 尝试播放
                        const audio = new Audio(audioUrl);
                        audio.play()
                            .then(() => alert("✅ 播放成功!"))
                            .catch(e => alert("❌ 播放失败: " + e.message)); // 8. 播放结果
                    })
                    .catch(error => {
                        alert("💥 发生严重错误: " + error.message); // 9. 全局错误捕获
                    });
            });
        });
    });
})();