浏览器读出文本window.speechSynthesis.speak(msg)

window.speechSynthesis.speak(msg)

是用于在浏览器中调用 Web Speech API 的语音合成功能。这段代码会让浏览器读出 msg 对象中的文本。

// 创建一个新的 SpeechSynthesisUtterance 对象
var msg = new SpeechSynthesisUtterance();

// 设置要朗读的文本
msg.text = "Hello, how are you?";

// 设置语言(可选)
msg.lang = "en-US"; // 英语(美国)
msg.lang = "zh-CN"; // 中文(简体)

// 设置语速、音调和音量(可选)
msg.rate = 1; // 语速,默认值是1
msg.pitch = 1; // 音调,默认值是1
msg.volume = 1; // 音量,范围是0到1

// 调用 speak() 方法来朗读文本
window.speechSynthesis.speak(msg);

参数解释:

  • msg.text: 要朗读的文本内容。
  • msg.lang: 朗读的语言和口音(例如 "en-US" 为美式英语,"zh-CN" 为简体中文)。
  • voice: 设置使用的语音。可以通过 speechSynthesis.getVoices() 获取系统支持的语音列表,并选择其中一个。
  • msg.rate: 朗读的语速,1 为正常速度。
  • msg.pitch: 朗读的音调,1 为正常音调。
  • msg.volume: 音量,范围是 0 到 1。

监听方法:

onstart: 当开始朗读时触发。

utterance.onstart = () => {
    console.log('Speech has started.');
};

onend: 当朗读结束时触发。

onerror: 当发生错误时触发。

onpause: 当朗读暂停时触发。

onresume: 当朗读恢复时触发。

onboundary: 当朗读到单词或句子边界时触发。可以用来实现更细粒度的控制,例如高亮显示当前朗读的单词。

 

语音列表

通过 speechSynthesis.getVoices() 获取系统支持的语音列表。可以选择特定的语音来朗读

const voices = speechSynthesis.getVoices();
console.log(voices); // 打印出所有可用的语音

// 设置语音
utterance.voice = voices.find(voice => voice.name === 'Google US English');

 

管理语音合成队列

Web Speech API 使用一个队列来管理要朗读的 SpeechSynthesisUtterance 实例。你可以在队列中添加多个 SpeechSynthesisUtterance,它们会按顺序被朗读。

const utterance1 = new SpeechSynthesisUtterance('First sentence.');
const utterance2 = new SpeechSynthesisUtterance('Second sentence.');
speechSynthesis.speak(utterance1);
speechSynthesis.speak(utterance2);

 

停止、暂停、恢复语音合成

speechSynthesis.cancel(): 停止所有正在进行的语音合成,并清空队列。

speechSynthesis.cancel();

speechSynthesis.pause(): 暂停当前正在进行的语音合成。 

speechSynthesis.pause();

speechSynthesis.resume(): 恢复暂停的语音合成。

const utterance = new SpeechSynthesisUtterance('Hello, this is a test.');
utterance.onstart = () => console.log('Speech started.');
utterance.onend = () => console.log('Speech ended.');
utterance.onerror = (event) => console.error('Error occurred:', event);

speechSynthesis.speak(utterance);

 

 

posted @   SimoonJia  阅读(357)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
历史上的今天:
2022-08-29 JS中绑定事件的5种方式
2022-08-29 Js获取头部链接URLSearchParams(location.search)
点击右上角即可分享
微信分享提示