V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
elza
V2EX  ›  分享发现

做单词网站时,我无意中发现了一个离线发音方法

  •  
  •   elza · 4 天前 · 564 次点击
    在开发一款在线背单词网站时,遇到的一个核心难题就是 单词发音。

    一些免费的 API (比如 dictionaryapi.dev )虽然好用,但存在 不稳定、可能失效 的问题。

    付费的 API (如 Oxford 、Cambridge 、Google Cloud TTS 等)音质好,但价格对个人开发者来说确实偏高。

    正在纠结时,我发现其实浏览器自带的 Web Speech API 就能完成发音功能。

    使用浏览器自带 TTS

    例如下面这段代码,就能让浏览器朗读单词:

    function getBestEnglishVoice() {
    const voices = speechSynthesis.getVoices();
    const preferred = [
    "Google US English",
    "Google UK English Female",
    "Google UK English Male",
    "Samantha",
    "Alex",
    "Microsoft Zira Desktop - English (United States)",
    "Microsoft David Desktop - English (United States)"
    ];
    for (let name of preferred) {
    const v = voices.find(voice => voice.name === name);
    if (v) return v;
    }
    return voices.find(voice => voice.lang.startsWith("en"));
    }

    const playPronunciation = (word: string) => {
    const utterance = new SpeechSynthesisUtterance(word);
    utterance.lang = "en-US";
    utterance.voice = getBestEnglishVoice();
    // utterance.rate = 0.9; // 可以调节语速
    speechSynthesis.speak(utterance);
    };


    我测试了一些常见单词,效果基本没问题。

    缺点就是
    不同浏览器 / 系统的发音不一致
    Chrome 、Safari 、Edge 各自调用的 TTS 引擎不同,音色和自然度差异很大。
    在 Windows 上听起来可能是“微软的机械音”,而在 macOS 上可能是接近 Siri 的发音。


    所以,这种方案只适合做 离线场景、个人学习的小项目。

    有没有其他方案,求分享。
    jookr
        1
    jookr  
       4 天前
    语音合成
    https://cloud.tencent.com/document/api/1073/37985
    有免费额度可试用

    语音纯代码,保存 html 可试听

    源码: https://netcut.cn/1j566qj1i
    keller
        2
    keller  
       4 天前
    关于   ·   帮助文档   ·   自助推广系统   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   1075 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 19ms · UTC 18:14 · PVG 02:14 · LAX 11:14 · JFK 14:14
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.