1. 介绍
本节为非规范性。
Web Speech API 的目标是使网页开发者能够在网页浏览器中提供语音输入和文本转语音输出功能,这些功能通常在使用标准语音识别或屏幕阅读器软件时不可用。 该 API 本身不依赖底层的语音识别和合成实现,既可以支持基于服务器的识别与合成,也可以支持基于客户端/嵌入式的识别与合成。 该 API 旨在同时支持简短(一次性)语音输入和连续语音输入。 语音识别结果以假设列表的形式提供给网页,并为每个假设提供其它相关信息。
本规范是 HTML Speech 孵化器小组最终报告 中定义的 API 的一个子集。 该报告完全属于参考性内容,因为它不是标准化进程的文档。 就本文件而言,该报告的所有部分都可视为参考性背景材料,并为本文件提供信息性的背景。 本规范是该报告的一个完全可用的子集。 具体而言,该子集不包括底层传输协议、对 HTML 标记的拟议扩展,并定义了一个简化的 JavaScript API 子集。 该子集支持孵化器小组最终报告中的大多数用例和示例代码。 该子集并不排除将来对标记、API 或底层传输协议进行标准化的可能性,事实上孵化器报告定义了此类未来工作的潜在路线图。
2. 用例
本节为非规范性。
本规范支持以下用例,如 孵化器报告第4节 中所定义。
- 语音网页搜索
- 语音命令界面
- 开放对话的连续识别
- 在无需可见 UI 时提供的语音用户界面
- 语音活动检测
- 用于提供视觉反馈的合成时间结构
- Hello World
- 语音翻译
- 支持语音的电子邮件客户端
- 对话系统
- 多模态交互
- 语音驾驶路线提示
- 多模态视频游戏
- 多模态搜索
为了保持 API 的最简性,本规范不直接支持以下用例。 这并不排除在将来作为 API 增强添加对此用例的支持,实际上孵化器报告为此提供了路线图。
- 重新识别
3. 安全与隐私注意事项
-
用户代理必须仅在获得明确且知情的用户同意后启动语音输入会话。
用户同意例如可以包括:
- 用户点击一个可见的语音输入元素,该元素具有明显的图形表示,表明它将启动语音输入。
- 接受作为对
start()调用结果显示的权限提示。 - 之前授予的始终允许此网页进行语音输入的同意。
-
当正在录制音频时,用户代理必须向用户给出明显的指示。
- 在图形用户代理中,这可以是由用户代理作为其浏览器界面的一部分显示的强制性通知,网页无法访问该通知。
例如,这可以是浏览器界面/地址栏中的跳动/闪烁的录音图标、状态栏中的指示、可听见的通知,或任何对用户来说相关且可访问的内容。
该 UI 元素还必须允许用户停止录音。
- 在仅语音的用户代理中,该指示例如可以采用系统朗读语音输入元素标签并随后发出短促哔声的形式。
- 在图形用户代理中,这可以是由用户代理作为其浏览器界面的一部分显示的强制性通知,网页无法访问该通知。
例如,这可以是浏览器界面/地址栏中的跳动/闪烁的录音图标、状态栏中的指示、可听见的通知,或任何对用户来说相关且可访问的内容。
该 UI 元素还必须允许用户停止录音。
- 用户代理也可以在首次使用语音输入时向用户给出更长的解释,让用户知道这是什么以及如何调整其隐私设置以在需要时禁用语音录制。
- 为减轻指纹识别的风险,当在
MediaStreamTrack上执行语音识别时,用户代理不得对语音识别进行个性化处理。
3.1. 实现考量
本节为非规范性。
- 口述密码输入从安全角度可能存在问题,但是否口述密码由用户自行决定。
- 语音输入可能被用于窃听用户。 恶意网页可能使用诸如隐藏输入元素或以其他方式让用户误以为已停止录音但仍在继续录制的手段。 它们也可能将输入元素样式化为看起来像其他东西,从而诱骗用户点击。 有关对文件输入元素进行样式化的示例可见于 https://www.quirksmode.org/dom/inputfile.html。 上述建议旨在降低此类攻击的风险。
4. API 描述
本节为规范性。
4.1. SpeechRecognition 接口
语音识别接口是用于控制给定识别过程的脚本化 Web API。
术语“最终结果”表示一个SpeechRecognitionResult
,其中 isFinal
属性为 true。
术语“中间结果”表示一个 SpeechRecognitionResult
,其中 isFinal
属性为 false。
SpeechRecognition
具有下列内部槽:
[[started]]-
表示语音识别是否已启动的布尔标志。初始值为
false。
[[processLocally]]-
指示是否必须在本地执行识别的布尔标志。初始值为
false。
[[phrases]]-
表示用于上下文偏置的短语列表的
ObservableArray,包含SpeechRecognitionPhrase对象。初始值为新的空ObservableArray。
[SecureContext ,Exposed =Window ]interface :SpeechRecognition EventTarget {(); // recognition parametersconstructor attribute SpeechGrammarList grammars ;attribute DOMString lang ;attribute boolean continuous ;attribute boolean interimResults ;attribute unsigned long maxAlternatives ;attribute boolean processLocally ;attribute ObservableArray <SpeechRecognitionPhrase >phrases ; // methods to drive the speech interactionundefined start ();undefined start (MediaStreamTrack );audioTrack undefined stop ();undefined abort ();static Promise <AvailabilityStatus >available (SpeechRecognitionOptions );options static Promise <boolean >install (SpeechRecognitionOptions ); // event methodsoptions attribute EventHandler ;onaudiostart attribute EventHandler ;onsoundstart attribute EventHandler ;onspeechstart attribute EventHandler ;onspeechend attribute EventHandler ;onsoundend attribute EventHandler ;onaudioend attribute EventHandler ;onresult attribute EventHandler ;onnomatch attribute EventHandler ;onerror attribute EventHandler ;onstart attribute EventHandler ; };onend dictionary {SpeechRecognitionOptions required sequence <DOMString >;langs boolean =processLocally false ; };enum {SpeechRecognitionErrorCode "no-speech" ,"aborted" ,"audio-capture" ,"network" ,"not-allowed" ,"service-not-allowed" ,"language-not-supported" ,"phrases-not-supported" };enum {AvailabilityStatus "unavailable" ,"downloadable" ,"downloading" ,"available" }; [SecureContext ,Exposed =Window ]interface :SpeechRecognitionErrorEvent Event {(constructor DOMString ,type SpeechRecognitionErrorEventInit );eventInitDict readonly attribute SpeechRecognitionErrorCode error ;readonly attribute DOMString message ; };dictionary :SpeechRecognitionErrorEventInit EventInit {required SpeechRecognitionErrorCode ;error DOMString = ""; }; // Item in N-best list [message SecureContext ,Exposed =Window ]interface {SpeechRecognitionAlternative readonly attribute DOMString transcript ;readonly attribute float confidence ; }; // A complete one-shot simple response [SecureContext ,Exposed =Window ]interface {SpeechRecognitionResult readonly attribute unsigned long length ;getter SpeechRecognitionAlternative item (unsigned long );index readonly attribute boolean isFinal ; }; // A collection of responses (used in continuous mode) [SecureContext ,Exposed =Window ]interface {SpeechRecognitionResultList readonly attribute unsigned long length ;getter SpeechRecognitionResult item (unsigned long ); }; // A full response, which could be interim or final, part of a continuous response or not [index SecureContext ,Exposed =Window ]interface :SpeechRecognitionEvent Event {(constructor DOMString ,type SpeechRecognitionEventInit );eventInitDict readonly attribute unsigned long resultIndex ;readonly attribute SpeechRecognitionResultList results ; };dictionary :SpeechRecognitionEventInit EventInit {unsigned long = 0;resultIndex required SpeechRecognitionResultList ; }; // The object representing a speech grammar. This interface has been deprecated and exists in this spec for the sole purpose of maintaining backwards compatibility. [results Exposed =Window ]interface {SpeechGrammar attribute DOMString src ;attribute float weight ; }; // The object representing a speech grammar collection. This interface has been deprecated and exists in this spec for the sole purpose of maintaining backwards compatibility. [Exposed =Window ]interface {SpeechGrammarList ();constructor readonly attribute unsigned long length ;getter SpeechGrammar item (unsigned long );index undefined addFromURI (DOMString ,src optional float = 1.0);weight undefined addFromString (DOMString ,string optional float = 1.0); }; // The object representing a phrase for contextual biasing. [weight SecureContext ,Exposed =Window ]interface {SpeechRecognitionPhrase constructor (DOMString ,phrase optional float = 1.0);boost readonly attribute DOMString phrase ;readonly attribute float boost ; };
4.1.1. SpeechRecognition 属性
grammarsattribute, of type SpeechGrammarList- grammars 属性存储表示此识别活动的 SpeechGrammar 对象集合。 在本规范中该属性不起作用,仅为保持向后兼容而存在。
langattribute, of type DOMString- 此属性将为请求设置识别的语言,使用有效的 BCP 47 语言标签。[BCP47] 如果未设置,脚本读取时保持未设置,但在打开与识别服务的连接时将默认使用 HTML 文档根元素及其关联层次的语言。 此默认值在输入请求打开连接到识别服务时计算并使用。
continuousattribute, of type boolean- 当 continuous 属性设置为 false 时,用户代理在响应启动识别时不得返回多于一个的最终结果, 例如单次交互模式。 当 continuous 属性设置为 true 时,用户代理在响应启动识别时必须返回零个或多个最终结果,表示多个连续识别, 例如听写模式。 默认值必须为 false。注意,此属性设置不影响中间结果。
interimResultsattribute, of type boolean- 控制是否返回中间结果。 当设置为 true 时,应返回中间结果。 当设置为 false 时,必须不返回中间结果。 默认值必须为 false。注意,此属性设置不影响最终结果。
maxAlternativesattribute, of type unsigned long- 此属性将设置每个结果的最大
SpeechRecognitionAlternative数量。 默认值为 1。 processLocallyattribute, of type boolean- 当此属性设置为 true 时,表示语音识别过程必须在用户设备本地执行。 如果设置为 false,用户代理可以在本地和远端处理之间进行选择。 默认值为 false。
phrasesattribute, of type ObservableArray<SpeechRecognitionPhrase>-
phrases属性提供用于上下文偏置的一系列SpeechRecognitionPhrase对象。它是一个ObservableArray, 可以像 JavaScriptArray一样修改(例如使用push())。- 获取器步骤为返回
[[phrases]]的值。 - 获取器步骤为返回
小组已讨论是否可以使用 WebRTC 来指定音频源选择和远端识别器。 参见 public-speech-api@w3.org 上的线程 Interacting with WebRTC, the Web Audio API and other external sources。
4.1.2. SpeechRecognition 方法
start()method-
从设备的麦克风启动语音识别过程。
调用时,执行以下步骤:
-
令 requestMicrophonePermission 为布尔变量并设为
true。 -
以 requestMicrophonePermission 运行 启动会话算法。
-
start(methodMediaStreamTrackaudioTrack)-
使用一个
MediaStreamTrack启动语音识别过程。 调用时,执行以下步骤:-
令 audioTrack 为第一个参数。
-
如果 audioTrack 的
kind属性不是"audio",抛出InvalidStateError并中止这些步骤。 -
如果 audioTrack 的
readyState属性不是"live",抛出InvalidStateError并中止这些步骤。 -
令 requestMicrophonePermission 为
false。 -
以 requestMicrophonePermission 运行 启动会话算法。
-
stop()method- stop 方法表示向识别服务发出停止监听更多音频的指令,并尝试使用它已接收到的音频返回结果。 stop 方法的典型用例例如网页应用中用户以按住说话的方式进行交互,类似对讲机。 终端用户可能按住空格键来与系统对话,在按下时会触发 start 调用,释放空格键时调用 stop 方法以确保系统不再监听用户。 一旦调用 stop 方法,语音服务必须不再收集附加音频并且不得继续监听用户。 语音服务必须尝试基于其已为该次识别收集的音频返回识别结果(或 nomatch)。 如果在已经停止或正在停止的对象上调用 stop(即从未对其调用过 start,或者其上已触发了 end 或 error 事件,或之前已对其调用过 stop),用户代理必须忽略该调用。
abort()method- abort 方法请求立即停止监听和识别并且不返回任何信息,只表示系统已完成。 当调用 abort 方法时,语音服务必须停止识别。 一旦语音服务不再连接,用户代理必须触发一个 end 事件。 如果在已经停止或正在中止的对象上调用 abort(即从未调用过 start,或者其上已触发了 end 或 error 事件,或之前已对其调用过 abort),用户代理必须忽略该调用。
available(methodSpeechRecognitionOptionsoptions)-
available方法返回一个Promise, 该 Promise 解析为一个AvailabilityStatus, 指示与SpeechRecognitionOptions参数匹配的可用性。 访问此方法受策略控制功能 “on-device-speech-recognition” 的限制,默认允许清单为'self'。调用时,执行下列步骤:
-
令 promise 为 一个新 Promise。
-
以 options 和 promise 运行 可用性算法。如果它返回异常,则抛出该异常并中止这些步骤。
-
返回 promise。
-
install(methodSpeechRecognitionOptionsoptions)-
install方法尝试为options.langs中指定的所有语言安装设备端语音识别语言包。 它返回一个Promise, 该 Promise 解析为一个boolean。 当对请求且受支持的语言的所有安装尝试成功(或这些语言已被安装)时,Promise 解析为true。 如果options.langs为空、并非所有请求的语言受支持,或任何对受支持语言的安装尝试失败,则 Promise 解析为false。 访问此方法受策略控制功能 “on-device-speech-recognition” 的限制,默认允许清单为'self'。调用时,执行下列步骤:
-
如果当前设置对象的相关全局对象的关联文档不是完全活动(fully active),则抛出
InvalidStateError并中止这些步骤。 -
如果 options 的
langs中的任何 lang 不是有效的 [BCP47] 语言标签,则抛出SyntaxError并中止这些步骤。 -
如果 options 的
langs中的任何 lang 的设备端语音识别语言包不受支持,则返回一个解析为 false 的Promise并跳过其余步骤。 -
令 promise 为 一个新 Promise。
-
对 options 的
langs中的每个 lang,开始下载该 lang 的设备端语音识别语言包。注意:用户代理可以提示用户显式许可下载设备端语音识别语言包。
-
在相关全局对象的任务队列上排队一个任务以运行以下步骤:
-
当为 options 指定的所有语言的下载成功时,使用
true解析 promise,否则使用false解析之。注意:Promise 的
false解析并不表明具体的失败原因。用户代理鼓励在开发者工具控制台消息中提供更详细的失败信息。但该详细错误信息不会暴露给脚本。
-
-
返回 promise。
processLocally在此算法中未被使用。
-
4.1.3. AvailabilityStatus 枚举值
AvailabilityStatus
枚举表示语音识别能力的可用性。其取值如下:
"unavailable"- 表示对于指定语言和处理偏好,语音识别不可用。
如果
processLocally为true,代表用户代理不支持该语言的设备端识别。 如果processLocally为false,代表至少有一个指定语言既不可本地识别,也不可远程识别。 "downloadable"- 表示用户代理支持指定语言的设备端语音识别,但尚未安装。可通过
install()方法进行安装。此状态主要在processLocally为 true 时适用。 "downloading"- 表示指定语言的设备端语音识别正在下载中。此状态主要在
processLocally为 true 时适用。 "available"- 表示对于所有指定语言及给定处理偏好,语音识别可用。
如果
processLocally为 true,表示设备端识别已安装且可用。 如果processLocally为 false,表示可用(可以是本地或远程识别)。
当调用带 options 和 promise 的 可用性算法 时,用户代理必须按照以下步骤执行:
-
如果 当前设置对象的 相关全局对象的 关联文档不是 完全活动,则抛出
InvalidStateError并中止这些步骤。 -
令 langs 为
langs(即 options 的 langs)。 -
如果 langs 中有任何 lang 不是有效的 [BCP47] 语言标签,抛出
SyntaxError并中止这些步骤。 -
如果
processLocally为false:-
如果 langs 为空序列,令 status 为
unavailable。 -
否则,如果所有 langs 都可用语音识别(可为远程),令 status 为
available。 -
否则,令 status 为
unavailable。
-
-
如果
processLocally为true:- 如果 langs 为空序列,令 status 为
unavailable。 -
否则:
- 令 finalStatus 为
available。 -
对 langs 中每一个 language:
- 定义 currentLanguageStatus。
- 如果 language 的设备端语音识别已安装,将 currentLanguageStatus 设为
available。 - 否则如其正在下载,将 currentLanguageStatus 设为
downloading。 - 否则如代理支持但尚未安装,将 currentLanguageStatus 设为
downloadable。 - 否则(不支持)设为
unavailable。 - 如果 currentLanguageStatus 在有序列表
[{{AvailabilityStatus/available}}, {{AvailabilityStatus/downloading}}, {{AvailabilityStatus/downloadable}}, {{AvailabilityStatus/unavailable}}]中排在 finalStatus 之后,则将 finalStatus 设为 currentLanguageStatus。
- 令 status 为 finalStatus。
- 令 finalStatus 为
- 如果 langs 为空序列,令 status 为
-
在相关全局对象的任务队列上排队任务,执行如下:
-
以 status 解析 promise。
-
当调用带 requestMicrophonePermission 的 启动会话算法 时,用户代理必须执行以下步骤:
-
如果 当前设置对象的 相关全局对象的 关联文档不是 完全活动,则抛出
InvalidStateError并中止这些步骤。 -
如果
[[started]]为true且未触发 error 或 end 事件,则抛出InvalidStateError并中止这些步骤。 -
如果 this.
phrases的length大于 0 且用户代理不支持上下文偏置: -
如果 this.
[[processLocally]]为true:-
如果用户代理判断本地语音识别不可用于 this.
lang,或无法满足本地处理要求:-
排队任务,触发名为 error 的事件于 this,事件对象类型为
SpeechRecognitionErrorEvent, 其error属性初始化为service-not-allowed,message为实现自定义字符串说明原因。 -
中止这些步骤。
-
-
-
将
[[started]]设为true。 -
如果 requestMicrophonePermission 为
true并且 请求麦克风权限 "microphone" 被 "拒绝" :-
排队任务,触发名为 error 的事件于 this,事件类型为
SpeechRecognitionErrorEvent, 其error属性为not-allowed,message为实现自定义字符串说明原因。 -
中止这些步骤。
-
4.1.4. SpeechRecognition 事件
语音识别事件遵循 DOM Level 2 事件模型。 应使用 EventTarget 接口中的方法注册事件监听器。 SpeechRecognition 接口还包含用于为每种事件类型注册单一事件处理器的方便属性。 这些事件不会冒泡,也不可取消。
对于所有这些事件,DOM Level 2 事件接口定义的 timeStamp 属性必须设置为事件对象所表示的真实世界事件发生时的最佳估算。 即使相关时间戳可能是在远端服务(如远程识别服务中的 speechend 事件)产生,该 timeStamp 也必须采用用户代理的本地时间视图。
除非另有规定,不同事件的触发顺序未定义。 例如,一些实现可能会在 audioend 之前触发 speechstart 或 speechend,如果音频检测在客户端,语音检测在服务端。
audiostartevent- 当用户代理开始捕获音频时触发。
soundstartevent- 当检测到某些声音(可能为语音)时触发。 必须以低延时触发,例如通过客户端能量检测器。 audiostart 事件总是先于 soundstart 事件触发。
speechstartevent- 将用于语音识别的语音开始时触发。 audiostart 事件总是先于 speechstart 事件触发。
speechendevent- 将用于语音识别的语音结束时触发。 speechstart 事件总是先于 speechend 事件触发。
soundendevent- 当不再检测到声音时触发。 必须以低延时触发,例如通过客户端能量检测器。 soundstart 事件总是先于 soundend 事件触发。
audioendevent- 当用户代理完成音频捕获时触发。 audiostart 事件总是先于 audioend 事件触发。
resultevent- 当语音识别器返回结果时触发。
事件对象采用
SpeechRecognitionEvent接口。 audiostart 事件总是先于 result 事件触发。 nomatchevent- 当语音识别器返回最终结果,但无任何识别假设达到或超过置信度阈值时触发。
事件对象采用
SpeechRecognitionEvent接口。 事件中的results属性可包含置信度低于阈值的结果或为 null。audiostart事件总是先于 nomatch 事件触发。 errorevent- 发生语音识别错误时触发。
事件对象采用
SpeechRecognitionErrorEvent接口。 startevent- 识别服务开始监听音频准备识别时触发。
endevent- 服务断开连接时触发。 不论会话因何原因结束,此事件总会生成。
4.1.5. SpeechRecognitionErrorEvent
SpeechRecognitionErrorEvent
接口用于 error 事件。
errorattribute, 类型为 SpeechRecognitionErrorCode,只读-
errorCode 是指出错原因的枚举。其取值为:
"no-speech"- 未检测到语音。
"aborted"- 语音输入因某种原因被中止,例如用户代理特定操作(如用户取消语音输入)。
"audio-capture"- 音频采集失败。
"network"- 完成识别所需的某些网络通信失败。
"not-allowed"- 出于安全、隐私等原因,用户代理不允许进行任何语音输入。
"service-not-allowed"- 用户代理不允许网页请求的语音服务,但会允许部分语音服务(例如不支持所选服务,或因安全、隐私等原因)。
"language-not-supported"- 该语言不被支持。
"phrases-not-supported"- 语音识别模型不支持用于上下文偏置的短语。
messageattribute, 类型为 DOMString,只读- message 内容由实现方自定义。 该属性主要用于调试,开发者不应将其直接用于应用的用户界面。
4.1.6. SpeechRecognitionAlternative
SpeechRecognitionAlternative 表示 n-best 列表中使用的响应的简单视图。
transcriptattribute, 类型为 DOMString, 只读- transcript 字符串表示用户说出的原始词语。 对于连续识别,在必要时必须包含首尾空格,以便将连续的 SpeechRecognitionResults 连接后能形成正确的会话转录文本。
confidenceattribute, 类型为 float,只读-
confidence 表示识别系统对于该识别正确性的置信度,取值为 0 到 1 之间的数值。
数值越大表示系统越自信。
小组讨论过置信度能否独立于语音识别引擎而指定,以及是否应包含置信度阈值和 nomatch,因为这不是对话 API。 参见 public-speech-api@w3.org 上的 Confidence property 讨论线程。
4.1.7. SpeechRecognitionResult
SpeechRecognitionResult 对象表示单次识别的匹配,可以是连续识别的一部分,也可以是非连续识别的全部返回结果。
lengthattribute, 类型为 unsigned long,只读- length 属性表示 item 数组中包含多少个 n-best 备选项。
item(index)getter- item getter 从 n-best 数组中按索引返回一个 SpeechRecognitionAlternative。 如果 index 大于等于 length,则返回 null。 用户代理必须确保 length 属性等于数组中的元素数。 用户代理必须确保 n-best 列表按照置信度不递增顺序排列(每个元素的置信度不大于前一个元素)。
isFinalattribute, 类型为 boolean,只读- final 布尔值若为 true,表示语音服务这是最后一次返回该索引的值。 如果为 false,则表示此为中间结果,可能还会发生更改。
4.1.8. SpeechRecognitionResultList
SpeechRecognitionResultList 对象包含代表完整连续识别返回结果的一系列识别结果。 对于非连续识别,它只包含一个值。
lengthattribute, 类型为 unsigned long,只读- length 属性表示 item 数组中包含多少个结果。
item(index)getter- item getter 从结果数组中按索引返回一个 SpeechRecognitionResult。 如果 index 大于等于 length,则返回 null。 用户代理必须确保 length 属性等于数组中的元素数。
4.1.9. SpeechRecognitionEvent
SpeechRecognitionEvent 是每当中间或最终结果发生任何更改时所触发的事件。
resultIndexattribute, 类型为 unsigned long,只读- resultIndex 必须设置为 "results" 数组中最先发生更改的索引。
resultsattribute, 类型为 SpeechRecognitionResultList,只读- 当前会话下所有识别结果的数组。 即所有已返回的最终结果,后跟所有中间结果的当前最佳假设。 必须由零个或多个最终结果后接零个或多个中间结果组成。 在后续 SpeechRecognitionResultEvent 事件中,中间结果可能会被更新为新的中间结果或最终结果,或被移除(当处于 "results" 数组末尾且数组长度减少时)。 最终结果不得被覆盖或移除。 所有索引小于 resultIndex 的条目与上一次触发 SpeechRecognitionResultEvent 时的数组完全一致。 所有等于或大于 resultIndex 的条目(若存在)将会被新结果覆盖。 "results" 数组的长度可以增加或减少,但不得小于 resultIndex。 注意当 resultIndex 等于 results.length 时,不会返回新结果,这可能发生在数组长度减少以移除一个或多个中间结果的情形。
4.1.10. SpeechRecognitionPhrase
SpeechRecognitionPhrase 对象表示用于上下文偏置的短语,具有如下内部槽:
[[phrase]]-
DOMString,表示需要提升的文本字符串。初始值为 null。 允许为空值但应被语音识别模型忽略。
[[boost]]-
float,约等于网站认为该短语较语音识别模型已知概率高的自然对数。 有效 boost 必须是 [0.0, 10.0] 区间内的 float 值,未指定时默认值为 1.0。 boost 为 0.0 表示完全不提升权重,越大 boost 表示该短语出现概率越高。 boost 取 10.0 表示该短语极有可能出现,一般很少设置。
SpeechRecognitionPhrase(phrase, boost)constructor-
当调用此构造函数时,执行如下步骤:
-
如果 boost 小于 0.0 或大于 10.0,抛出
SyntaxError并中止这些步骤。 -
令 phr 为新建的
SpeechRecognitionPhrase对象。 -
设置 phr.
[[phrase]]为 phrase 的值。 -
设置 phr.
[[boost]]为 boost 的值。 -
返回 phr。
-
phraseattribute, 类型为 DOMString,只读- 该属性返回
[[phrase]]的值。 boostattribute, 类型为 float,只读- 该属性返回
[[boost]]的值。
4.1.11. SpeechGrammar
SpeechGrammar 对象表示语法的容器。
语法支持已废弃并移除。grammar 对象仅为向后兼容保留,不影响语音识别。
此结构具有以下属性:
srcattribute, 类型为 DOMString- 必填的 src 属性是语法的 URI。
weightattribute, 类型为 float- 可选的 weight 属性控制该语法的权重,默认为 1。 较大权重正向提升该语法,较小权重则降低其权重。
4.1.12. SpeechGrammarList
SpeechGrammarList 对象表示 SpeechGrammar 对象的合集。 该结构具有以下属性:
语法支持已废弃并移除。grammar 对象仅为向后兼容保留,不影响语音识别。
lengthattribute, 类型为 unsigned long,只读- length 属性表示当前数组中有多少个语法。
item(index)getter- item getter 按索引从语法数组中返回一个 SpeechGrammar。 用户代理必须确保 length 属性等于数组中元素数量。 用户代理必须确保索引顺序(从小到大)与语法被添加到数组时的顺序一致。
addFromURI(src, weight)method- 该方法根据 URI 将语法添加到 grammars 数组参数中。 语法的 URI 由 src 参数指定,表示语法的 URI。 注意,部分服务可能支持可通过 URI 指定的内置语法。 weight 参数表示此语法相对于其他语法的权重。
addFromString(string, weight)method- 该方法根据文本将语法添加到 grammars 数组参数中。 语法内容由 string 参数指定。 创建 SpeechGrammar 对象时应将该内容编码为 data: URI。 weight 参数表示此语法相对于其他语法的权重。
4.2. SpeechSynthesis 接口
SpeechSynthesis 接口是用于控制文本转语音输出的脚本化 Web API。
[Exposed =Window ]interface :SpeechSynthesis EventTarget {readonly attribute boolean pending ;readonly attribute boolean speaking ;readonly attribute boolean paused ;attribute EventHandler ;onvoiceschanged undefined speak (SpeechSynthesisUtterance );utterance undefined cancel ();undefined pause ();undefined resume ();sequence <SpeechSynthesisVoice >getVoices (); };partial interface Window { [SameObject ]readonly attribute SpeechSynthesis ; }; [speechSynthesis Exposed =Window ]interface :SpeechSynthesisUtterance EventTarget {(constructor optional DOMString );text attribute DOMString text ;attribute DOMString lang ;attribute SpeechSynthesisVoice ?voice ;attribute float volume ;attribute float rate ;attribute float pitch ;attribute EventHandler ;onstart attribute EventHandler ;onend attribute EventHandler ;onerror attribute EventHandler ;onpause attribute EventHandler ;onresume attribute EventHandler ;onmark attribute EventHandler ; }; [onboundary Exposed =Window ]interface :SpeechSynthesisEvent Event {(constructor DOMString ,type SpeechSynthesisEventInit );eventInitDict readonly attribute SpeechSynthesisUtterance utterance ;readonly attribute unsigned long charIndex ;readonly attribute unsigned long charLength ;readonly attribute float elapsedTime ;readonly attribute DOMString name ; };dictionary :SpeechSynthesisEventInit EventInit {required SpeechSynthesisUtterance ;utterance unsigned long = 0;charIndex unsigned long = 0;charLength float = 0;elapsedTime DOMString = ""; };name enum {SpeechSynthesisErrorCode "canceled" ,"interrupted" ,"audio-busy" ,"audio-hardware" ,"network" ,"synthesis-unavailable" ,"synthesis-failed" ,"language-unavailable" ,"voice-unavailable" ,"text-too-long" ,"invalid-argument" ,"not-allowed" , }; [Exposed =Window ]interface :SpeechSynthesisErrorEvent SpeechSynthesisEvent {(constructor DOMString ,type SpeechSynthesisErrorEventInit );eventInitDict readonly attribute SpeechSynthesisErrorCode error ; };dictionary :SpeechSynthesisErrorEventInit SpeechSynthesisEventInit {required SpeechSynthesisErrorCode ; }; [error Exposed =Window ]interface {SpeechSynthesisVoice readonly attribute DOMString voiceURI ;readonly attribute DOMString name ;readonly attribute DOMString lang ;readonly attribute boolean localService ;readonly attribute boolean default ; };
4.2.1. SpeechSynthesis 属性
pending属性, 类型为 boolean,只读- 如果全局 SpeechSynthesis 实例的队列包含尚未开始朗读的发音对象,则该属性为 true。
speaking属性, 类型为 boolean,只读- 如果正在朗读发音对象,该属性为 true。 具体来说,当发音对象已开始朗读且尚未完成朗读时为 true。 这与全局 SpeechSynthesis 实例是否处于暂停状态无关。
paused属性, 类型为 boolean,只读- 当全局 SpeechSynthesis 实例处于暂停状态时,该属性为 true。 此状态与队列中是否有内容无关。 新窗口的全局 SpeechSynthesis 实例的默认状态为非暂停。
4.2.2. SpeechSynthesis 方法
speak(utterance)方法- 该方法将 SpeechSynthesisUtterance 对象 utterance 加入全局 SpeechSynthesis 实例队列尾部。 不会改变 SpeechSynthesis 实例的暂停状态。 如果实例处于暂停状态,将保持暂停。 如果未暂停且队列中无其他发音对象,则立即朗读该发音对象;否则该发音对象将排队,待前面的发音对象朗读完毕后朗读。 若调用该方法后到对应的 end 或 error 事件发生前修改了 SpeechSynthesisUtterance 对象, 不保证修改会影响朗读内容,且此类修改可能导致返回错误。 SpeechSynthesis 对象会独占该发音对象所有权。 作为 speak() 参数传给其它 SpeechSynthesis 实例时会抛出异常。 (例如两个同源 iframe 均含各自的 SpeechSynthesis 对象。)
cancel()方法- 该方法移除队列中所有发音对象。 若正在朗读发音对象,会立即停止朗读。 该方法不会改变全局 SpeechSynthesis 实例的暂停状态。
pause()方法- 该方法令全局 SpeechSynthesis 实例进入暂停状态。 若正在朗读发音对象,将在中间暂停。 (若已处于暂停状态则无操作。)
resume()方法- 该方法令全局 SpeechSynthesis 实例进入非暂停状态。 若发音对象正被朗读,将从暂停点继续朗读;否则将朗读队列中下一个发音对象(如有)。 (若已处于非暂停状态则无操作。)
getVoices()方法- 该方法返回可用的语音。 哪些语音可用取决于用户代理。 若无语音,或可用语音列表尚未知晓(例如服务器端合成异步确定), 本方法需返回长度为零的 SpeechSynthesisVoiceList。
4.2.3. SpeechSynthesis 事件
voiceschanged事件- 当 getVoices 方法返回的 SpeechSynthesisVoiceList 内容发生变化时触发。 例如:服务器端合成异步确定列表,或本地语音被安装/卸载。
4.2.4. SpeechSynthesisUtterance 属性
text属性, 类型为 DOMString- 该属性指定要合成和朗读的文本。 可以是纯文本或完整、结构良好的 SSML 文档。[SSML] 如语音合成引擎不支持 SSML 或仅支持部分标签,用户代理或语音引擎需将不支持的标签剥离朗读。 可能存在最大文本长度限制,如 32767 字符。
lang属性, 类型为 DOMString- 该属性指定发音对象的语音合成用语言,使用有效的 BCP 47 语言标签。[BCP47] 若未设置,则脚本读取时保持 unset,但默认使用 html 文档根元素及层级的语言。 默认值在打开与识别服务的连接时计算并使用。
voice属性, 类型为 SpeechSynthesisVoice,可为 null- 该属性指定网页应用希望使用的语音合成语音。
创建
SpeechSynthesisUtterance对象时,初始值为 null。 若调用speak()时本属性为SpeechSynthesisVoice对象列表中的一项,用户代理需使用该语音。 若调用speak()时未设置或为 null,则用户代理应使用默认语音。 默认语音应支持当前语言(见lang), 可为本地或远程服务,也可反映用户在浏览器参数等界面做的选择。 volume属性, 类型为 float- 该属性指定发音对象的朗读音量, 取值 [0,1],0 为最小音量,1 为最大音量,默认值为 1。 若使用 SSML,标记中的 prosody 标签会覆盖该值。
rate属性, 类型为 float- 该属性指定发音对象朗读语速。 相对于该语音的默认速度。 1 为语音引擎支持的默认速度(应为正常语速),2 为 2 倍,0.5 为一半速度。 不允许低于 0.1 或高于 10,实际语音合成引擎可约束更窄范围。 若使用 SSML,prosody 标签会覆盖该值。
pitch属性, 类型为 float- 该属性指定发音对象朗读音高。 取值 [0,2],0 为最低音高,2 为最高音高,1 为语音合成引擎/语音的默认音高。 语音合成引擎可能进一步约束取值范围。 若使用 SSML,prosody 标签会覆盖该值。
4.2.5. SpeechSynthesisUtterance 事件
这些事件均需使用 SpeechSynthesisEvent
接口,
唯有 error 事件需使用 SpeechSynthesisErrorEvent
接口。
这些事件不冒泡且不可取消。
start事件- 本发音开始朗读时触发。
end事件- 本发音朗读完成时触发。 若触发本事件,则不应再对本发音触发 error 事件。
error事件- 若发生导致本发音朗读失败的错误时触发。 若触发本事件,则不应再对本发音触发 end 事件。
pause事件- 发音在朗读中被暂停时触发。
resume事件- 发音在被暂停后恢复朗读时触发。 若将发音添加到队列时 SpeechSynthesis 实例处于暂停,接着调用 resume, 不会触发 resume 事件,发音朗读开始时将触发 start 事件。
mark事件- 发音到达 SSML 的命名 "mark" 标签时触发。[SSML] 若合成引擎提供该事件,用户代理必须触发它。
boundary事件- 发音到达单词或句子边界时触发。 若合成引擎提供该事件,用户代理必须触发它。
4.2.6. SpeechSynthesisEvent 属性
utterance属性, 类型为 SpeechSynthesisUtterance,只读- 包含触发本事件的 SpeechSynthesisUtterance。
charIndex属性, 类型为 unsigned long,只读- 指示当前朗读位置最接近的原始发音字符串的字符下标(从零开始)。 不保证 charIndex 与单词边界对齐,仅保证该索引前的字符已朗读,之后未读。 如合成引擎支持,用户代理需返回该值,否则返回 0。
charLength属性, 类型为 unsigned long,只读- 表示对应此事件将要朗读的文本(单词或句子)的长度。
以字符个数计,自本事件的
charIndex起算。 若合成引擎支持或能够确定,用户代理需返回该值,否则返回 0。 elapsedTime属性, 类型为 float,只读- 表示自本发音开始朗读以来本事件发生时的时间,单位为秒。 若合成引擎支持或能确定,用户代理需返回该值,否则返回 0。
name属性, 类型为 DOMString,只读- 对于 mark 事件,该属性为 SSML 中 mark 元素的 name 属性。[SSML] 对于 boundary 事件,为导致事件的边界类型:"word" 或 "sentence"。 其它事件应返回 ""。
4.2.7. SpeechSynthesisErrorEvent 属性
SpeechSynthesisErrorEvent 是为 SpeechSynthesisUtterance error 事件所用的接口。
error属性, 类型为 SpeechSynthesisErrorCode,只读-
errorCode 是指出错原因的枚举。其取值如下:
"canceled"- cancel 方法调用导致 SpeechSynthesisUtterance 在开始朗读前被移出队列。
"interrupted"- cancel 方法调用导致 SpeechSynthesisUtterance 在朗读进行中被中断且未完成。
"audio-busy"- 由于用户代理无法访问音频输出设备,当前无法完成操作。 (例如用户需关闭其它应用程序以释放设备。)
"audio-hardware"- 由于用户代理无法识别音频输出设备,当前无法完成操作。 (例如需连接扬声器或配置系统参数。)
"network"- 由于部分所需的网络通信失败,当前无法完成操作。
"synthesis-unavailable"- 由于没有可用的合成引擎,当前无法完成操作。 (如用户需安装或配置合成引擎。)
"synthesis-failed"- 由于合成引擎出错,操作失败。
"language-unavailable"- 未找到适合 SpeechSynthesisUtterance lang 指定语言的语音。
"voice-unavailable"- SpeechSynthesisUtterance voice 属性指定的语音不可用。
"text-too-long"- SpeechSynthesisUtterance text 属性内容过长,无法合成。
"invalid-argument"- SpeechSynthesisUtterance 的 rate、pitch 或 volume 属性内容不被合成器支持。
"not-allowed"- 当前环境下,用户代理或系统不允许语音合成启动。
4.2.8. SpeechSynthesisVoice 属性
voiceURI属性, 类型为 DOMString,只读- voiceURI 属性指定语音合成所用语音及其服务位置。 注意 voiceURI 是通用 URI,可指向本地或远程服务,可用具意义的 URN 或用被用户代理识别为本地服务的 URL。
name属性, 类型为 DOMString,只读- 该属性为语音的人类可读名称。 并不保证所有返回的名称唯一。
lang属性, 类型为 DOMString,只读- 该属性为 BCP 47 语言标签,表示语音的语言。[BCP47]
localService属性, 类型为 boolean,只读- 本地语音合成器提供的语音为 true,远程合成服务提供的为 false。 (远程服务可能有额外延迟带宽或成本,本地语音则可能质量较低,但都不保证必然如此。)
default属性, 类型为 boolean,只读- 每种语言至多有一个语音其属性为 true。 每种语言可有不同默认语音。 默认语音取决于用户代理如何决定。
5. 示例
本节为非规范性。
5.1. 语音识别示例
使用语音识别填写输入框并进行网页搜索。
< script type = "text/javascript" > var recognition= new SpeechRecognition(); recognition. onresult= function ( event) { if ( event. results. length> 0 ) { q. value= event. results[ 0 ][ 0 ]. transcript; q. form. submit(); } } </ script > < form action = "https://www.example.com/search" > < input type = "search" id = "q" name = "q" size = 60 > < input type = "button" value = "点击说话" onclick = "recognition.start()" > </ form >
使用语音识别将候选结果填入选项列表。
< script type = "text/javascript" > var recognition= new SpeechRecognition(); recognition. maxAlternatives= 10 ; recognition. onresult= function ( event) { if ( event. results. length> 0 ) { var result= event. results[ 0 ]; for ( var i= 0 ; i< result. length; ++ i) { var text= result[ i]. transcript; select. options[ i] = new Option( text, text); } } } function start() { select. options. length= 0 ; recognition. start(); } </ script > < select id = "select" ></ select > < button onclick = "start()" > 点击说话</ button >
使用连续语音识别填写文本域。
< textarea id = "textarea" rows = 10 cols = 80 ></ textarea > < button id = "button" onclick = "toggleStartStop()" ></ button > < script type = "text/javascript" > var recognizing; var recognition= new SpeechRecognition(); recognition. continuous= true ; reset(); recognition. onend= reset; recognition. onresult= function ( event) { for ( var i= event. resultIndex; i< event. results. length; ++ i) { if ( event. results[ i]. isFinal) { textarea. value+= event. results[ i][ 0 ]. transcript; } } } function reset() { recognizing= false ; button. innerHTML= "点击说话" ; } function toggleStartStop() { if ( recognizing) { recognition. stop(); reset(); } else { recognition. start(); recognizing= true ; button. innerHTML= "点击停止" ; } } </ script >
使用连续语音识别,将最终结果显示为黑色、中间结果显示为灰色。
< button id = "button" onclick = "toggleStartStop()" ></ button > < div style = "border:dotted;padding:10px" > < span id = "final_span" ></ span > < span id = "interim_span" style = "color:grey" ></ span > </ div > < script type = "text/javascript" > var recognizing; var recognition= new SpeechRecognition(); recognition. continuous= true ; recognition. interimResults= true ; reset(); recognition. onend= reset; recognition. onresult= function ( event) { var final = "" ; var interim= "" ; for ( var i= 0 ; i< event. results. length; ++ i) { if ( event. results[ i]. isFinal) { final += event. results[ i][ 0 ]. transcript; } else { interim+= event. results[ i][ 0 ]. transcript; } } final_span. innerHTML= final ; interim_span. innerHTML= interim; } function reset() { recognizing= false ; button. innerHTML= "点击说话" ; } function toggleStartStop() { if ( recognizing) { recognition. stop(); reset(); } else { recognition. start(); recognizing= true ; button. innerHTML= "点击停止" ; final_span. innerHTML= "" ; interim_span. innerHTML= "" ; } } </ script >
5.2. 语音合成示例
朗读文本。
< script type = "text/javascript" > speechSynthesis. speak( new SpeechSynthesisUtterance( 'Hello World' )); </ script >
带属性和事件的朗读文本。
< script type = "text/javascript" > var u= new SpeechSynthesisUtterance(); u. text= 'Hello World' ; u. lang= 'en-US' ; u. rate= 1.2 ; u. onend= function ( event) { alert( 'Finished in ' + event. elapsedTime+ ' seconds.' ); } speechSynthesis. speak( u); </ script >
致谢
Adam Sobieski (Phoster) Björn Bringert (Google) Charles Pritchard Dominic Mazzoni (Google) Gerardo Capiel (Benetech) Jerry Carter Kagami Sascha Rosylight Marcos Cáceres (Mozilla) Nagesh Kharidi (Openstream) Olli Pettay (Mozilla) Peter Beverloo (Google) Raj Tumuluri (Openstream) Satish Sampath (Google)
另外,感谢 HTML Speech 孵化小组成员,以及创建本规范依据的最终报告。