字典API音频功能无法启用的代码问题求助
字典API音频功能修复方案
你的代码目前未实现音频播放的核心逻辑,导致功能失效,以下是问题点对应修复方案:
核心问题与修复步骤
- 未提取API中的音频链接:Dictionary API返回的数据包含发音音频URL,你需要从接口返回的
data中取出对应地址,赋值给sound元素的src属性 - 缺少
playSound函数实现:按钮点击调用了该函数,但代码中未定义它 - 未处理异常场景:输入不存在的单词时API会返回错误,需要做异常处理避免页面无响应
修复后的完整代码
const url = "https://api.dictionaryapi.dev/api/v2/entries/en/"; const result = document.getElementById("result"); const sound = document.getElementById("sound"); const btn = document.getElementById("search-btn"); // 实现音频播放函数 function playSound() { sound.play(); } btn.addEventListener("click", () => { let inpWord = document.getElementById("inp-word").value.trim(); if (!inpWord) return; // 空输入直接终止执行 fetch(`${url}${inpWord}`) .then((response) => { if (!response.ok) throw new Error("未找到该单词"); return response.json(); }) .then((data) => { // 提取第一个可用的音频链接 const audioUrl = data[0].phonetics.find(item => item.audio)?.audio; if (!audioUrl) { result.innerHTML = `<p>该单词无可用音频资源</p>`; return; } sound.src = audioUrl; // 更新页面展示内容 result.innerHTML = ` <div class="word"> <h3>${inpWord}</h3> <button onclick="playSound()"> <i class="fas fa-volume-up"></i> </button> </div> `; }) .catch((err) => { result.innerHTML = `<p>${err.message}</p>`; }); });
关键说明
- 从API返回的
data[0].phonetics数组中筛选带audio属性的项,拿到音频链接后赋值给sound元素 - 确保你的HTML中存在
<audio id="sound"></audio>标签,否则sound变量会为null - 添加空输入判断和API错误捕获,提升体验稳定性
内容的提问来源于stack exchange,提问作者Prince K. Owureku
相关产品推荐
相关产品推荐

