You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

字典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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 11:20:56