gpt4 book ai didi

javascript - 即使支持,speechSynthesis 也无法在移动 Safari 上运行

转载 作者:行者123 更新时间:2023-12-01 15:26:55 26 4
gpt4 key购买 nike

我正在尝试使用 SpeechSynthesis API。它适用于桌面浏览器和移动 Chrome,但不适用于移动 Safari。

  const msg = new SpeechSynthesisUtterance("Hello World");
window.speechSynthesis.speak(msg);

我添加了一个小测试,似乎 Safari 支持 API,这可能是它不起作用的权限问题吗?
  if ("speechSynthesis" in window) {
alert("yay");
} else {
alert("no");
}

最佳答案

就我而言,问题分解为正确的加载中移动 Safari 上的语音合成。

有一些事情要按顺序检查:

  • 声音加载了吗?
  • 语音甚至安装在您的系统上吗?
  • 话语配置是否正确?
  • 是从用户交互事件中调用的 speak 函数吗?

  • 以下示例总结了这些检查并适用于 MacOS 桌面浏览器和 iOS Safari:

    let _speechSynth
    let _voices
    const _cache = {}

    /**
    * retries until there have been voices loaded. No stopper flag included in this example.
    * Note that this function assumes, that there are voices installed on the host system.
    */

    function loadVoicesWhenAvailable (onComplete = () => {}) {
    _speechSynth = window.speechSynthesis
    const voices = _speechSynth.getVoices()

    if (voices.length !== 0) {
    _voices = voices
    onComplete()
    } else {
    return setTimeout(function () { loadVoicesWhenAvailable(onComplete) }, 100)
    }
    }

    /**
    * Returns the first found voice for a given language code.
    */

    function getVoices (locale) {
    if (!_speechSynth) {
    throw new Error('Browser does not support speech synthesis')
    }
    if (_cache[locale]) return _cache[locale]

    _cache[locale] = _voices.filter(voice => voice.lang === locale)
    return _cache[locale]
    }

    /**
    * Speak a certain text
    * @param locale the locale this voice requires
    * @param text the text to speak
    * @param onEnd callback if tts is finished
    */

    function playByText (locale, text, onEnd) {
    const voices = getVoices(locale)

    // TODO load preference here, e.g. male / female etc.
    // TODO but for now we just use the first occurrence
    const utterance = new window.SpeechSynthesisUtterance()
    utterance.voice = voices[0]
    utterance.pitch = 1
    utterance.rate = 1
    utterance.voiceURI = 'native'
    utterance.volume = 1
    utterance.rate = 1
    utterance.pitch = 0.8
    utterance.text = text
    utterance.lang = locale

    if (onEnd) {
    utterance.onend = onEnd
    }

    _speechSynth.cancel() // cancel current speak, if any is running
    _speechSynth.speak(utterance)
    }

    // on document ready
    loadVoicesWhenAvailable(function () {
    console.log("loaded")
    })

    function speak () {
    setTimeout(() => playByText("en-US", "Hello, world"), 300)
    }
    <button onclick="speak()">speak</button>


    代码的详细信息作为注释添加到代码段中。

    关于javascript - 即使支持,speechSynthesis 也无法在移动 Safari 上运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61658740/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com