Web语音API

社区组报告草案,

关于本文档的更多细节
本版本:
https://webaudio.github.io/web-speech-api/
问题跟踪:
GitHub
规范内
编辑者:
Evan Liu (Google)
前编辑者:
André Natal (Mozilla)
Glen Shires (Google)
Philip Jägenstedt (Google)
Hans Wennborg (Google)
测试:
web-platform-tests speech-api/ (进行中)

摘要

本规范定义了一个 JavaScript API,使网页开发者能够在其网页中集成语音识别和语音合成功能。 它使开发者能够用脚本生成文本转语音输出,并将语音识别用作表单输入、连续听写及控制输入。 JavaScript API 允许网页控制激活与时机,并处理结果及备选项。

本文档状态

1. 介绍

本节为非规范性。

Web Speech API 的目标是使网页开发者能够在网页浏览器中提供语音输入和文本转语音输出功能,这些功能通常在使用标准语音识别或屏幕阅读器软件时不可用。 该 API 本身不依赖底层的语音识别和合成实现,既可以支持基于服务器的识别与合成,也可以支持基于客户端/嵌入式的识别与合成。 该 API 旨在同时支持简短(一次性)语音输入和连续语音输入。 语音识别结果以假设列表的形式提供给网页,并为每个假设提供其它相关信息。

本规范是 HTML Speech 孵化器小组最终报告 中定义的 API 的一个子集。 该报告完全属于参考性内容,因为它不是标准化进程的文档。 就本文件而言,该报告的所有部分都可视为参考性背景材料,并为本文件提供信息性的背景。 本规范是该报告的一个完全可用的子集。 具体而言,该子集不包括底层传输协议、对 HTML 标记的拟议扩展,并定义了一个简化的 JavaScript API 子集。 该子集支持孵化器小组最终报告中的大多数用例和示例代码。 该子集并不排除将来对标记、API 或底层传输协议进行标准化的可能性,事实上孵化器报告定义了此类未来工作的潜在路线图。

2. 用例

本节为非规范性。

本规范支持以下用例,如 孵化器报告第4节 中所定义。

为了保持 API 的最简性,本规范不直接支持以下用例。 这并不排除在将来作为 API 增强添加对此用例的支持,实际上孵化器报告为此提供了路线图。

3. 安全与隐私注意事项

  1. 用户代理必须仅在获得明确且知情的用户同意后启动语音输入会话。 用户同意例如可以包括:
    • 用户点击一个可见的语音输入元素,该元素具有明显的图形表示,表明它将启动语音输入。
    • 接受作为对 start() 调用结果显示的权限提示。
    • 之前授予的始终允许此网页进行语音输入的同意。
  2. 当正在录制音频时,用户代理必须向用户给出明显的指示。
    • 在图形用户代理中,这可以是由用户代理作为其浏览器界面的一部分显示的强制性通知,网页无法访问该通知。 例如,这可以是浏览器界面/地址栏中的跳动/闪烁的录音图标、状态栏中的指示、可听见的通知,或任何对用户来说相关且可访问的内容。 该 UI 元素还必须允许用户停止录音。
      示例 UI 录音通知。
    • 在仅语音的用户代理中,该指示例如可以采用系统朗读语音输入元素标签并随后发出短促哔声的形式。
  3. 用户代理也可以在首次使用语音输入时向用户给出更长的解释,让用户知道这是什么以及如何调整其隐私设置以在需要时禁用语音录制。
  4. 为减轻指纹识别的风险,当在 MediaStreamTrack 上执行语音识别时,用户代理不得对语音识别进行个性化处理。

3.1. 实现考量

本节为非规范性。

  1. 口述密码输入从安全角度可能存在问题,但是否口述密码由用户自行决定。
  2. 语音输入可能被用于窃听用户。 恶意网页可能使用诸如隐藏输入元素或以其他方式让用户误以为已停止录音但仍在继续录制的手段。 它们也可能将输入元素样式化为看起来像其他东西,从而诱骗用户点击。 有关对文件输入元素进行样式化的示例可见于 https://www.quirksmode.org/dom/inputfile.html。 上述建议旨在降低此类攻击的风险。

3.2. 设备端模型隐私注意事项

本节为非规范性内容。

3.2.1. 语言包可用性

对于设备端语音识别,语言包的确切下载状态可能成为指纹识别途径。该途径提供的信息位数取决于传给 available() 或 install() 的选项,以及这些选项如何影响下载(例如,不同语言包是否具有不同的可用性状态)。

3.2.1.1. 下载状态掩蔽

为防止跨源指纹识别和站点串通,本规范要求用户代理按存储键对语言包可用性进行分区,并默认让 available() 返回 "downloadable",以掩蔽当前下载状态,即使用户设备上的底层语言包已处于 "available" 或 "downloading" 状态也是如此(参见 available() 下针对下载掩蔽状态的下载掩蔽要求,以及可用性算法的此步骤)。

对于给定的(options,存储键)元组,其下载掩蔽状态只有在该存储键内的网页显式调用 install() 后才会解除掩蔽(参见 install() 的此步骤);而且 start() 也会将被掩蔽的语言包视为不可用于本地语音识别(参见启动会话算法的此步骤)。因此,网页只有执行成本更高的操作(例如消耗一次用户激活或触发用户权限提示)后,才能获知真实下载状态(参见安装时的阻力)。

要求在该存储键的其他存储被清除时清除下载掩蔽状态,可防止已解除掩蔽的状态在存储重置后继续存在。

3.2.1.2. 安装时的阻力

下载状态掩蔽中描述的缓解措施可防范利用 available() 静默进行指纹识别的尝试。本规范还通过引入阻力,规定了防止 install() 被轻易用于指纹识别的要求:

此外,对于给定语言,通过 install() 发起下载过程基本上是一次性操作。可用性状态只有经过这些受保护的安装操作,才会从 "downloadable" 变为 "downloading",再变为 "available"。也就是说,虽然可以利用 install() 读取其中一些指纹信息位(通过观察其 promise 的兑现以及随后对 available() 的调用),但这样做会改变状态,从而实际上“销毁”这些信息位。

(有关可能多次下载的情况,以及如何在这些情况下保持隐私和安全的详细说明,参见取消下载、下载内容逐出和语言包占用的磁盘空间。)

3.2.1.3. 取消下载

由于语言包可用性严格按存储键分区(参见下载状态掩蔽),网页只能观察自身分区内的下载状态。

因此,如果用户代理依照 install() 的取消规则,因页面控制的操作(例如导航、页面卸载或 iframe 被销毁)而取消正在进行的下载,只要取消操作不改变其他存储键可观察到的可用性状态,所产生的状态变化(例如从 "downloading" 恢复为 "downloadable")就只对该特定存储键可见。这可防止取消行为被用作跨源指纹识别途径。

3.2.1.4. 下载内容逐出

为确保网站无法反复切换可用性状态,还需确保用户代理不对已下载语言包使用网页可间接控制的、基于配额的逐出系统。例如,如果用户代理在安装新语言包时逐出较久未使用的语言包,网页就可能触发这种逐出来切换目标语言包的状态。

为避免这种情况,install() 的下载内容逐出规则不鼓励允许网页控制已下载语言包逐出的系统,包括通过后续下载等间接触发方式进行控制。满足这一要求的一种方法是,绝不因网页发起的存储压力而逐出已下载内容,而是在下载新内容会造成存储压力时拒绝下载(例如使 install() 兑现为 false)。

响应用户控制的操作(例如通过浏览器设置界面)而逐出下载内容并无问题。

3.2.2. 敏感语言信息

即使缓解了可用性状态带来的指纹识别风险,得知用户已下载某个特定语言包(例如少数群体语言的语言包)也可能涉及敏感信息。

因此,除安装时的阻力外,install() 算法的此步骤还允许用户代理在认为有助于保护隐私时模拟下载(例如延迟 install() promise 的兑现,同时为该存储键报告 "downloading"),而不是在语言包已经存在时让 install() 立即兑现。这提供了合理的否认空间:如果 install() 几秒后才兑现为 true,这既可能是模拟的延迟,也可能是真实而快速的下载。

这类模拟延迟并非万无一失,但仍有一定隐私收益,尤其是在与权限提示等其他缓解措施结合时。

3.2.3. 模型版本

设备端语音识别模型的具体版本或行为也可能成为指纹识别途径。本 API 不直接公开模型版本。

防止模型版本成为指纹识别途径的最佳方法,是将其与用户代理版本绑定,使模型的版本(及行为)只随已经公开的信息(例如 User-Agent 字符串)一起更新。因此,available() 下的模型版本规则鼓励在通过 available() 判断语言包是否为 "available" 时,限制单一用户代理版本可搭配的模型版本数量。这可能包括不再向旧版用户代理提供模型更新,或在用户代理更新后忽略低于最低版本阈值的已下载模型(此时 available() 可能会为较新版本报告 "downloadable")。

这里存在权衡:将新版用户代理严格绑定到新版模型,可能增加 "available" 与 "downloadable" 之间的转换。可在下载新模型期间允许新版用户代理使用旧模型,保持 "available" 状态,以缓解这一问题;但这会短暂地允许识别使用旧模型与新版用户代理组合的用户。

3.2.4. 用户输入和语音数据

语音数据本身就很敏感。processLocally 下的用户输入保留规则禁止实现使用通过本 API 获得的用户语音输入来训练或微调设备端语音识别模型,也禁止以模型将来可查询的方式存储用户语音输入(例如用于当前会话之外或跨源的个性化)。

以这种方式使用用户语音输入会造成严重的隐私泄露,可能将用户信息或从用户与某一站点交互中推导出的信息暴露给另一站点。

这强化了安全和隐私注意事项中已有的要求:对 MediaStreamTrack 进行语音识别时不得对识别进行个性化;这一要求也广泛适用于通过本 API 由设备端模型处理的任何语音。

3.2.5. 云端实现与设备端实现

Web Speech API 可支持基于服务器(云端)和基于客户端/嵌入式(设备端)的识别与合成。processLocally 属性允许开发者表明必须在设备端进行处理。

当 processLocally 为 false(默认值)时,用户语音数据可能被发送到远程服务器处理。如果没有显式要求本地处理,Web 开发者就需要了解这种可能性及其隐私影响;同时,关于语音处理发生的位置,鼓励用户代理向用户清楚说明。

当 processLocally 为 true 时,本“设备端模型隐私注意事项”一节中的考量尤为重要。

3.3. 设备端模型安全注意事项

本节为非规范性内容。

3.3.1. 语言包占用的磁盘空间

通过 install() 下载设备端语音识别语言包,可能占用用户大量磁盘空间。

根据 install() 的存储压力规则,出现存储压力时,预期用户代理会权衡设备端语音识别的实用性与语言包占用的磁盘空间;可以让新下载的 install() 兑现为 false,或通过其他方式释放空间,同时注意下载内容逐出中讨论的隐私影响,并可通过下载时提示或用于管理已下载语言包的浏览器界面让用户参与决策。

如果先前安装的语言包在可能正被使用或预期可用时被逐出(例如由用户操作或因严重存储压力),只要模型仍在内存中,正在进行或后续的会话就可能继续工作;但一旦该语言包不再可用,尝试使用它(例如将 lang 设为该语言、processLocally 设为 true 后调用 start())就应当妥善失败。这可能包括 available() 返回 "downloadable"(若不再支持则为 "unavailable"),以及 start() 触发带有 service-not-allowed 或 language-not-supported 等适当错误码的 SpeechRecognitionErrorEvent。

3.3.2. 运行时共享资源

设备端语音识别可能大量消耗 CPU、内存乃至专用硬件加速器等运行时资源。

根据启动会话算法的运行时资源要求,预期用户代理会确保,一个网页使用设备端语音识别不会过度干扰另一个网页使用本 API、另一个网页的正常运行或整个系统的稳定性。

本规范不强制采用特定的缓解策略,但可行方法包括请求排队、速率限制或检测滥用行为,并在防止资源耗尽或不稳定所必需时,使语音识别操作失败(例如触发带有 service-not-allowed 的 SpeechRecognitionErrorEvent)。

3.3.3. 操作系统提供的模型

设备端语音识别的一种实现策略是委托底层操作系统提供的模型或功能进行处理。这可能带来一致的用户体验和高效的资源利用等好处。

不过,这种方式也伴随着向 Web 暴露操作系统功能时的常见考量。根据 processLocally 下的操作系统提供模型的要求,即使用户代理对模型行为的控制较少,使用操作系统提供的模型时仍需确保满足本规范的全部隐私和安全要求。尤其值得注意的要求包括不使用用户语音输入进行训练(参见用户输入和语音数据)以及公平且稳定的资源共享(参见运行时共享资源)。

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 {
    constructor();

    // recognition parameters
    attribute SpeechGrammarList grammars;
    attribute DOMString lang;
    attribute boolean continuous;
    attribute boolean interimResults;
    attribute boolean unspokenPunctuation;
    attribute unsigned long maxAlternatives;
    attribute boolean processLocally;
    attribute ObservableArray<SpeechRecognitionPhrase> phrases;

    // methods to drive the speech interaction
    undefined start();
    undefined start(MediaStreamTrack audioTrack);
    undefined stop();
    undefined abort();
    static Promise<SpeechRecognitionAvailabilityStatus> available(SpeechRecognitionOptions options);
    static Promise<boolean> install(SpeechRecognitionOptions options);

    // event methods
    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;
};

enum SpeechRecognitionQuality {
  "command",
  "dictation",
  "conversation"
};

dictionary SpeechRecognitionOptions {
  required sequence<DOMString> langs;
  boolean processLocally = false;
  SpeechRecognitionQuality quality = "command";
};

enum SpeechRecognitionErrorCode {
    "no-speech",
    "aborted",
    "audio-capture",
    "network",
    "not-allowed",
    "service-not-allowed",
    "language-not-supported",
    "phrases-not-supported"
};

enum SpeechRecognitionAvailabilityStatus {
    "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 message = "";
};

// Item in N-best list
[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;
    readonly attribute double speechStartTime;
    readonly attribute double speechEndTime;
};

// A collection of responses (used in continuous mode)
[SecureContext, Exposed=Window]
interface SpeechRecognitionResultList {
    readonly attribute unsigned long length;
    getter SpeechRecognitionResult? item(unsigned long index);
};

// A full response, which could be interim or final, part of a continuous response or not
[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 resultIndex = 0;
    required SpeechRecognitionResultList results;
};

// The object representing a speech grammar. This interface has been deprecated and exists in this spec for the sole purpose of maintaining backwards compatibility.
[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 weight = 1.0);
    undefined addFromString(DOMString string,
                    optional float weight = 1.0);
};

// The object representing a phrase for contextual biasing.
[SecureContext, Exposed=Window]
interface SpeechRecognitionPhrase {
    constructor(DOMString phrase, optional float boost = 1.0);
    readonly attribute DOMString phrase;
    readonly attribute float boost;
};

4.1.1. SpeechRecognition 属性

grammars attribute, of type SpeechGrammarList
grammars 属性存储表示此识别活动的 SpeechGrammar 对象集合。 在本规范中该属性不起作用,仅为保持向后兼容而存在。
lang attribute, of type DOMString
此属性将为请求设置识别的语言,使用有效的 BCP 47 语言标签。[BCP47] 如果未设置,脚本读取时保持未设置,但在打开与识别服务的连接时将默认使用 HTML 文档根元素及其关联层次的语言。 此默认值在输入请求打开连接到识别服务时计算并使用。
continuous attribute, of type boolean
当 continuous 属性设置为 false 时,用户代理在响应启动识别时不得返回多于一个的最终结果, 例如单次交互模式。 当 continuous 属性设置为 true 时,用户代理在响应启动识别时必须返回零个或多个最终结果,表示多个连续识别, 例如听写模式。 默认值必须为 false。注意,此属性设置不影响中间结果。
interimResults attribute, of type boolean
控制是否返回中间结果。 当设置为 true 时,应返回中间结果。 当设置为 false 时,必须不返回中间结果。 默认值必须为 false。注意,此属性设置不影响最终结果。
unspokenPunctuation 属性, 类型为 boolean
此属性控制语音识别引擎是否自动推断并插入标点符号 (例如句号、逗号和问号),这些标点符号基于自然停顿、语法 结构和韵律,而无需用户明确说出标点命令。 默认值必须为 false。
maxAlternatives 属性,类型为 unsigned long
此属性将设置每个结果中 SpeechRecognitionAlternative 的最大数量。 默认值为 1。
processLocally 属性,类型为 boolean
此属性在设置为 true 时,表示要求语音识别过程必须在用户设备上本地执行。 如果设置为 false,则用户代理可以在本地处理和远程处理之间进行选择。 默认值为 false。

当 processLocally 为 false 时,用户语音数据可能被发送到远程服务器处理;用户代理应当向用户清楚说明语音处理发生的位置(参见云端实现与设备端实现)。

无论 processLocally 的值为何,实现都不得使用通过本 API 获得的用户语音输入来训练或微调设备端语音识别模型,也不得以模型将来可查询的方式存储用户语音输入(例如用于当前会话之外或跨源的个性化;参见用户输入和语音数据)。

将设备端语音识别委托给底层操作系统提供的模型或功能时,即使用户代理对模型行为的控制较少,也必须确保满足本规范的全部隐私和安全要求(参见操作系统提供的模型)。

phrases 属性,类型为 ObservableArray<SpeechRecognitionPhrase>
phrases 属性提供一个 SpeechRecognitionPhrase 对象列表,用于上下文偏置。这是一个 ObservableArray, 可以像 JavaScript Array 一样修改(例如,使用 push())。
getter 步骤是返回 [[phrases]] 的值。

小组已讨论是否可以使用 WebRTC 来指定音频源选择和远端识别器。 参见 public-speech-api@w3.org 上的线程 Interacting with WebRTC, the Web Audio API and other external sources。

4.1.2. SpeechRecognition 方法

start() 方法
直接通过设备上的麦克风启动语音识别过程。 调用时,运行以下步骤:
  1. 令 requestMicrophonePermission 为设置为 true 的布尔变量。

  2. 使用 requestMicrophonePermission 运行启动会话算法。

start(MediaStreamTrack audioTrack) 方法
使用 MediaStreamTrack 启动语音识别过程。 调用时,运行以下步骤:
  1. 令 audioTrack 为第一个参数。

  2. 如果 audioTrack 的 kind 属性不为 "audio", 则抛出 InvalidStateError 并中止这些步骤。

  3. 如果 audioTrack 的 readyState 属性不为 "live",则抛出 InvalidStateError 并中止这些步骤。

  4. 令 requestMicrophonePermission 为 false。

  5. 运行启动会话算法,参数为 requestMicrophonePermission 和 audioTrack。

stop() 方法
stop 方法表示指示识别服务停止侦听更多音频, 并尝试仅使用它已经为此次识别接收到的音频返回结果。 stop 方法的典型用途可能是由最终用户执行结束 指示的 Web 应用,类似于对讲机。 最终用户可以按住空格键与系统对话,在按下空格键时 已经发生 start 调用,而当释放空格键时,将调用 stop 方法,以确保 系统不再侦听用户。 一旦调用 stop 方法,语音服务就不得收集额外的音频,也不得 继续侦听用户。 语音服务必须尝试根据它已经为此次识别 收集的音频返回识别结果(或 nomatch)。 如果在已经停止或正在停止的对象上调用 stop 方法(即从未对其 调用 start、已经在其上触发 end 或 error 事件,或者先前已经 对其调用 stop),则用户代理必须忽略该调用。
abort() 方法
abort 方法请求立即停止侦听并停止识别,不返回任何 信息,只表示系统已经完成操作。 调用 abort 方法时,语音服务必须停止识别。 一旦语音服务不再连接,用户代理必须触发 end 事件。 如果在已经停止或正在中止的对象上调用 abort 方法(即从未对其 调用 start、已经在其上触发 end 或 error 事件,或者先前已经 对其调用 abort),则用户代理必须忽略该调用。
available(SpeechRecognitionOptions options) 方法
available 方法返回一个 Promise, 该 Promise 会兑现为一个 SpeechRecognitionAvailabilityStatus 指示与 SpeechRecognitionOptions 参数(包括请求的 quality 级别)相匹配的识别可用性。 对此方法的访问受名为 "on-device-speech-recognition" 的策略控制特性限制, 该特性的默认允许列表为 'self'。

为防止跨源指纹识别和站点串通,用户代理必须按存储键对设备端语言包可用性进行分区。当 processLocally 为 true 时,用户代理必须默认让 available() 返回 "downloadable" 来掩蔽当前下载状态,即使用户设备上的实际底层语言包处于 "available" 或 "downloading" 状态也是如此(参见可用性算法的此步骤和下载状态掩蔽)。每个(options,存储键)元组都建立此下载掩蔽状态(具体而言,对于给定的存储键,按 options 的 langs 中每种语言和 quality 建立,忽略 processLocally)。用户代理必须仅在该键内的网页以给定选项显式调用 install(),且该调用成功发起下载(或加入正在进行的下载),或兑现为 true(表示语言包已就绪;参见 install() 的此步骤)后,才将特定(options,存储键)元组的状态设为 "unmasked"。实现必须确保,每当该存储键的其他存储被清除时,基于存储键的下载掩蔽状态也被清除。

用户代理在通过 available() 判断语言包是否为 "available" 时,应当限制单一用户代理版本可搭配的设备端模型版本数量(例如,将模型更新与用户代理更新绑定;或在用户代理更新后忽略低于最低版本阈值的已下载模型,改为对较新版本报告 "downloadable";参见模型版本)。

调用时,运行以下步骤:

  1. 令 promise 为一个新的 Promise。

  2. 使用 options 和 promise 运行可用性算法。

  3. 返回 promise。

install(SpeechRecognitionOptions options) 方法
install 方法尝试为 options.langs 中指定的所有语言安装与请求的 quality 等级下限匹配的语音识别语言包。它返回一个兑现为 boolean 的 Promise。当请求且受支持的语言的所有安装尝试均成功时(或语言已安装),promise 兑现为 true。如果 options.langs 为空、并非所有请求的语言都受支持,或任何受支持语言的安装尝试失败,promise 兑现为 false。如果此调用将发起下载,但调用的 Window 没有瞬时激活,则以 NotAllowedError 拒绝 promise。对本方法的访问受策略控制的功能 "on-device-speech-recognition" 限制,其默认允许列表为 'self'。

调用时,运行以下步骤:

  1. 令 promise 为 一个新的 Promise。

  2. 如果该 当前设置对象的 相关全局对象的 关联的 Document并非 完全活跃,则拒绝 promise,错误为 InvalidStateError, 中止这些步骤并返回 promise。

  3. 如果 langs 在 options 中为空序列,则将 promise 兑现为 false,中止这些步骤并返回 promise。

  4. 如果任一 lang 在 langs (属于 options)中不是有效的 [BCP47] 语言标签,则拒绝 promise,错误为 SyntaxError, 中止这些步骤并返回 promise。

  5. 如果任一 lang 在 langs (属于 options)中对应的设备端语音识别语言包不受支持,则将 promise 兑现为 false, 中止这些步骤并返回 promise。

  6. 如果针对 options 的 available() 将兑现为 "downloadable"(按 options 的 processLocally 为 true 的情况求值),即从调用网页所能观察到的情况看,此调用会发起下载,则:

    1. 如果当前设置对象的相关全局对象没有瞬时激活,则以 NotAllowedError 拒绝 promise,中止这些步骤,并返回 promise。

    2. 以当前设置对象的相关全局对象为参数,消耗用户激活。

    注意:由于 available() 受下载掩蔽状态规则约束,此检查基于被掩蔽的可用性状态,而非真实下载状态。因此,install() 是否要求瞬时激活,不会向仍被掩蔽的网页泄露真实下载状态。

  7. 并行地运行以下步骤:

    1. 用户代理可以提示用户明确授权下载设备端语音识别语言包,也可以根据隐式信号(例如观察到的滥用模式;参见安装时的阻力)或存储压力拒绝发起下载。出现存储压力时,用户代理应当权衡设备端语音识别的实用性与语言包占用的磁盘空间(可以拒绝新下载或通过其他方式释放磁盘空间,但须符合下述逐出要求;参见语言包占用的磁盘空间),并可以让用户参与这些决策(例如通过下载时的权限提示或用于管理已下载语言包的浏览器界面)。如果不允许下载,则在相关全局对象的任务队列上将一个任务加入队列,将 promise 兑现为 false,然后中止这些步骤。

    2. 对于 options 的 langs 中的每个 lang,发起下载与请求的 quality 等级下限匹配的 lang 设备端语音识别语言包(仅在尚未安装且未在下载时)。

    3. 如果已为 options 的 langs 中的每个 lang 成功发起下载(或其语言包已经安装或正在下载),则将(options,存储键)的下载掩蔽状态设为 "unmasked"。

    4. 等待 options 的 langs 指定的所有语言下载成功或失败。如果用户代理认为有助于保护隐私,可以模拟下载(例如在兑现 promise 前增加延迟),而非在语言包已经存在时立即兑现(参见敏感语言信息)。在这种模拟下载期间,用户代理必须为该存储键报告 "downloading" 可用性状态(并在该存储键可观察到的其他用途上将语言包视为尚未安装,包括启动会话算法以及可用性算法的 processLocally 为 false 的分支),使网页无法区分模拟延迟与真实下载。

    5. 如果所有这些语言均下载成功,则令 result 为 true,否则令 result 为 false。

    6. 在 任务排队,将任务加入 相关全局对象的 任务队列,以便 使用 result 兑现 promise。

      注意:Promise 兑现为 false 并不表示 具体的失败原因。鼓励用户代理在开发者工具控制台消息中提供更详细的 失败信息。但是,这些 详细的错误信息不会暴露给脚本。

  8. 返回 promise。

    本算法不使用 options 的 processLocally 值:install() 始终针对设备端语言包,因此上面的可用性检查将该值视为 true。

当发起请求的文档被销毁或导航离开时,用户代理可以按照其标准资源管理策略取消正在进行的语言包下载,前提是这不会改变任何其他存储键可观察到的可用性状态(例如,不取消另一个存储键也正在等待的底层下载;参见取消下载)。

用户代理不应实现允许网页控制已下载语言包逐出的系统,包括通过后续下载等间接触发方式控制(例如,因网页发起的存储压力而采用基于配额或最近最少使用的逐出方式;参见下载内容逐出)。允许响应用户控制的操作(例如通过浏览器设置界面)而逐出下载内容。

4.1.3. SpeechRecognitionAvailabilityStatus 枚举值

SpeechRecognitionAvailabilityStatus 枚举表示语音识别功能的可用性。其值如下:

"unavailable"
表示指定语言的语音识别在所选处理 偏好下不可用。 如果 processLocally (属于 options)为 true,则表示该语言的设备端语音识别不 受用户代理支持。 如果 processLocally (属于 options)为 false,则表示至少一种指定语言既无法使用本地语音识别, 也无法使用远程语音识别。
"downloadable"
表示用户代理支持对指定语言进行设备端语音识别, 但尚未安装。可以使用 install() 方法进行安装。这一状态主要适用于 processLocally (属于 options)为 true 的情况。
"downloading"
表示指定语言的设备端语音识别语言包目前正处于 下载过程中。这一状态主要适用于 processLocally (属于 options)为 true 的情况。
"available"
表示所有指定语言在给定的处理 偏好下均可使用语音识别。 如果 processLocally (属于 options)为 true,则表示设备端语音识别已安装并准备就绪。 如果 processLocally (属于 options)为 false,则表示语音识别可用(可能是本地或远程识别)。

4.1.4. SpeechRecognitionQuality 枚举值

SpeechRecognitionQuality 枚举指示为语音识别模型请求的语义能力和质量级别下限。 其值为:

"command"
级别 1:短语、单个说话者、有限词汇量(例如,用于智能家居或 简单应用的语音命令)。
"dictation"
级别 2:连续语音、中等背景噪声、单个主要说话者(例如,SMS/Email 之类的长文本 输入)。
"conversation"
级别 3:多说话者、复杂词汇量、高噪声容忍度(例如,会议转录和 连续字幕)。

当调用带 options 和 promise 的 可用性算法 时,用户代理必须按照以下步骤执行:

  1. 如果当前设置对象的相关全局对象的关联的 Document并非完全活跃,则以 InvalidStateError 拒绝 promise 并中止这些步骤。

  2. 令 langs 为 langs (属于 options)。

  3. 如果 langs 中的任一 lang 不是有效的 [BCP47] 语言标签,则以 SyntaxError 拒绝 promise 并中止这些步骤。

  4. 如果 processLocally (属于 options)为 false:

    1. 如果 langs 为空序列,则令 status 为 unavailable。

    2. 否则,如果 langs 中的所有 language 都可使用语音识别(可以是远程识别;若其下载掩蔽状态对于调用者的存储键为 "unmasked",也可以是设备端识别),则令 status 为 available。

    3. 否则,令 status 为 unavailable。

  5. 如果 processLocally (属于 options)为 true:

    1. 如果 langs 为空序列,则令 status 为 unavailable。
    2. 否则:
      1. 令 finalStatus 为 available。
      2. 对于 langs 中的每个 language:
        1. 令 currentLanguageStatus。
        2. 如果已安装与 options 所请求的 quality 匹配的 language 设备端语音识别模型(考虑模型版本限制),且调用者的存储键没有依据the install() algorithm进行模拟下载,则将 currentLanguageStatus 设为 available。
        3. 否则,如果正在下载与 options 所请求的 quality 匹配的 language 设备端语音识别模型(包括依据the install() algorithm为调用者的存储键进行的模拟下载),则将 currentLanguageStatus 设为 downloading。
        4. 否则,如果用户代理支持与 options 所请求的 quality 匹配的 language 设备端语音识别,但尚未安装,则将 currentLanguageStatus 设为 downloadable。
        5. 否则(不支持 language 的设备端语音识别), 将 currentLanguageStatus 设置为 unavailable。
        6. 如果 currentLanguageStatus 为 available 或 downloading,且(options,存储键)的下载掩蔽状态对 language 而言不是 "unmasked",则将 currentLanguageStatus 设为 downloadable。
        7. 如果 currentLanguageStatus 在 finalStatus 之后,按照以下 有序列表中的顺序: [{{SpeechRecognitionAvailabilityStatus/available}}, {{SpeechRecognitionAvailabilityStatus/downloading}}, {{SpeechRecognitionAvailabilityStatus/downloadable}}, {{SpeechRecognitionAvailabilityStatus/unavailable}}], 则将 finalStatus 设置为 currentLanguageStatus。
      3. 令 status 为 finalStatus。
  6. 将一个任务加入队列,放入相关全局对象的任务队列,以运行以下 步骤:

    • 以 status 兑现 promise。

当 启动 会话算法 以 requestMicrophonePermission 和 audioTrack(若已提供)为参数被调用时,用户代理 必须执行 以下步骤:

  1. 如果 当前设置对象的 相关全局对象的 关联 Document未处于 完全活动状态,则抛出一个 InvalidStateError 并中止这些步骤。

  2. 如果 [[started]] 为 true,且没有 error 事件或 end 事件 在其上触发过,则抛出一个 InvalidStateError 并中止这些步骤。

  3. 如果 this.phrases的 length 大于 0,且用户代理不支持上下文偏置:

    1. 将一个任务加入队列,以 触发一个事件,名称为 error,目标为 this,使用 SpeechRecognitionErrorEvent 并将其 error 属性初始化为 phrases-not-supported,并将其 message 属性设为由实现定义且详细说明原因的字符串。

    2. 中止这些步骤。

  4. 无论 this.[[processLocally]] 的值为何,用户代理必须将对于调用者的存储键而言下载掩蔽状态不是 "unmasked" 的设备端语言包,视为不可用于本地语音识别。如果 this.[[processLocally]] 为 true,或用户代理以其他方式尝试执行本地语音识别(例如不支持或未使用远程语音识别时):

    1. 如果用户代理确定本地语音识别对于 this.lang 不可用(包括其下载掩蔽状态对于调用者的存储键不是 "unmasked",或先前安装的语言包已被逐出而不再可用;参见下载掩蔽要求和下述逐出后的失败处理要求),或因其他原因无法完成本地处理(例如防止资源耗尽):

      1. 将一个任务加入队列,使用 SpeechRecognitionErrorEvent 在 this 上触发事件,事件名为 error,将其 error 属性初始化为 service-not-allowed,并将其 message 属性设为详述原因的、由实现定义的字符串。该字符串不得泄露对于调用者的存储键而言下载掩蔽状态不是 "unmasked" 的语言包是否已安装或正在下载。

      2. 中止这些步骤。

  5. 将 [[started]] 设为 true。

  6. 如果 requestMicrophonePermission 为 true,且 请求权限以使用 "microphone" 的结果为 "denied":

    1. 将一个任务加入队列,以 触发一个事件,名称为 error,目标为 this,使用 SpeechRecognitionErrorEvent 并将其 error 属性初始化为 not-allowed 并将其 message 属性设为由实现定义且详细说明原因的字符串。

    2. 中止这些步骤。

  7. 开始从音频源读取音频(MediaStreamTrack 若已提供,则使用它,否则使用麦克风);如果识别服务 尚未就绪,则缓冲帧。 这会建立识别会话的 会话音频时间线,该时间线度量已经过的 音频时长(以秒为单位),在读取第一帧音频时从 0.0 开始,并 随随后读取的每一帧音频的时长而推进。

  8. 一旦系统成功开始监听以进行识别,将一个任务加入队列,以 触发一个事件,名称为 start,目标为 this。

如果先前安装的语言包在可能正被使用或预期可用时被逐出(例如由用户操作或因严重存储压力),只要模型仍在内存中,正在进行或后续的会话可以继续工作;一旦该语言包不再可用,尝试使用它(例如将 lang 设为该语言、processLocally 设为 true 后调用 start())应当妥善失败(例如 available() 返回 "downloadable",若不再支持则返回 "unavailable";start() 触发带有 service-not-allowed 等适当错误码的 SpeechRecognitionErrorEvent,若不再支持则使用 language-not-supported;参见语言包占用的磁盘空间)。

用户代理应当确保,一个网页使用设备端语音识别不会过度干扰另一个网页使用本 API、另一个网页的正常运行或整个系统的稳定性(例如通过请求排队、速率限制或检测滥用行为;参见运行时共享资源)。如果为防止资源耗尽或不稳定所必需,用户代理可以使语音识别操作失败(例如触发带有 service-not-allowed 的 SpeechRecognitionErrorEvent)。设备端语音识别会话还受 processLocally 下的用户输入保留规则和操作系统提供模型的规则约束。

4.1.5. SpeechRecognition 事件

语音识别事件遵循 DOM Level 2 事件模型。 应使用 EventTarget 接口中的方法注册事件监听器。 SpeechRecognition 接口还包含用于为每种事件类型注册单一事件处理器的方便属性。 这些事件不会冒泡,也不可取消。

对于所有这些事件,DOM Level 2 事件接口定义的 timeStamp 属性必须设置为事件对象所表示的真实世界事件发生时的最佳估算。 即使相关时间戳可能是在远端服务(如远程识别服务中的 speechend 事件)产生,该 timeStamp 也必须采用用户代理的本地时间视图。

除非另有规定,不同事件的触发顺序未定义。 例如,一些实现可能会在 audioend 之后触发 speechstart 或 speechend,如果音频检测在客户端,语音检测在服务端。

audiostart event
当用户代理开始捕获音频时触发。
soundstart event
当检测到某些声音(可能为语音)时触发。 必须以低延时触发,例如通过客户端能量检测器。 audiostart 事件总是先于 soundstart 事件触发。
speechstart event
将用于语音识别的语音开始时触发。 audiostart 事件总是先于 speechstart 事件触发。
speechend event
将用于语音识别的语音结束时触发。 speechstart 事件总是先于 speechend 事件触发。
soundend event
当不再检测到声音时触发。 必须以低延时触发,例如通过客户端能量检测器。 soundstart 事件总是先于 soundend 事件触发。
audioend event
当用户代理完成音频捕获时触发。 audiostart 事件总是先于 audioend 事件触发。
result event
当语音识别器返回结果时触发。 事件对象采用 SpeechRecognitionEvent 接口。 audiostart 事件总是先于 result 事件触发。
nomatch event
当语音识别器返回最终结果,但无任何识别假设达到或超过置信度阈值时触发。 事件对象采用 SpeechRecognitionEvent 接口。 事件中的 results 属性可包含置信度低于阈值的结果或为 null。 audiostart 事件总是先于 nomatch 事件触发。
error event
发生语音识别错误时触发。 事件对象采用 SpeechRecognitionErrorEvent 接口。
start event
识别服务开始监听音频准备识别时触发。
end event
服务断开连接时触发。 不论会话因何原因结束,此事件总会生成。

4.1.6. SpeechRecognitionErrorEvent

SpeechRecognitionErrorEvent 接口用于 error 事件。

error attribute, 类型为 SpeechRecognitionErrorCode,只读
errorCode 是指出错原因的枚举。其取值为:
"no-speech"
未检测到语音。
"aborted"
语音输入因某种原因被中止,例如用户代理特定操作(如用户取消语音输入)。
"audio-capture"
音频采集失败。
"network"
完成识别所需的某些网络通信失败。
"not-allowed"
出于安全、隐私等原因,用户代理不允许进行任何语音输入。
"service-not-allowed"
用户代理不允许网页请求的语音服务,但会允许部分语音服务(例如不支持所选服务,或因安全、隐私等原因)。
"language-not-supported"
该语言不被支持。
"phrases-not-supported"
语音识别模型不支持用于上下文偏置的短语。
message attribute, 类型为 DOMString,只读
message 内容由实现方自定义。 该属性主要用于调试,开发者不应将其直接用于应用的用户界面。

4.1.7. SpeechRecognitionAlternative

SpeechRecognitionAlternative 表示 n-best 列表中使用的响应的简单视图。

transcript attribute, 类型为 DOMString, 只读
transcript 字符串表示用户说出的原始词语。 对于连续识别,在必要时必须包含首尾空格,以便将连续的 SpeechRecognitionResults 连接后能形成正确的会话转录文本。
confidence attribute, 类型为 float,只读
confidence 表示识别系统对于该识别正确性的置信度,取值为 0 到 1 之间的数值。 数值越大表示系统越自信。

小组讨论过置信度能否独立于语音识别引擎而指定,以及是否应包含置信度阈值和 nomatch,因为这不是对话 API。 参见 public-speech-api@w3.org 上的 Confidence property 讨论线程。

4.1.8. SpeechRecognitionResult

SpeechRecognitionResult 对象表示单次识别的匹配,可以是连续识别的一部分,也可以是非连续识别的全部返回结果。

length 属性, 其 类型为 unsigned long,只读
long 属性表示 item 数组中包含的 n-best 候选项数量。
item(index) 获取器
item 获取器根据 n-best 值数组中的 index 返回一个 SpeechRecognitionAlternative。 如果 index 大于或等于 length,则返回 null。 用户代理必须确保 length 属性被设为数组中的元素数量。 用户代理必须确保 n-best 列表按置信度非递增顺序排序(每个 元素的置信度必须小于或等于前面元素的置信度)。
isFinal 属性, 其 类型为 boolean,只读
最终结果布尔值必须设为 true,如果这是语音服务最后一次返回此 特定索引值。 如果该值为 false,则表示一个仍可能发生变化的临时结果。
speechStartTime 属性, 类型为 double,只读
一个 double 值,表示此识别结果对应的语音片段的起点,以偏移量表示,单位为 秒,所在时间线为 会话音频时间线。
speechEndTime 属性, 类型为 double,只读
一个 double 值,表示此识别结果对应的语音片段的终点,以偏移量表示,单位为 秒,所在时间线为 会话音频时间线。

speechStartTime 和 speechEndTime 是 会话音频时间线上的偏移量,而不是系统时钟的读数。 因此,它们不受音频输出延迟或以下时钟间漂移的影响:音频设备时钟与 系统时钟;无论识别以实时速度还是快于实时的速度运行,它们都相同。 其精度由实现定义。

4.1.9. SpeechRecognitionResultList

SpeechRecognitionResultList 对象包含代表完整连续识别返回结果的一系列识别结果。 对于非连续识别,它只包含一个值。

length attribute, 类型为 unsigned long,只读
length 属性表示 item 数组中包含多少个结果。
item(index) getter
item getter 从结果数组中按索引返回一个 SpeechRecognitionResult。 如果 index 大于等于 length,则返回 null。 用户代理必须确保 length 属性等于数组中的元素数。

4.1.10. SpeechRecognitionEvent

SpeechRecognitionEvent 是每当中间或最终结果发生任何更改时所触发的事件。

resultIndex attribute, 类型为 unsigned long,只读
resultIndex 必须设置为 "results" 数组中最先发生更改的索引。
results attribute, 类型为 SpeechRecognitionResultList,只读
当前会话下所有识别结果的数组。 即所有已返回的最终结果,后跟所有中间结果的当前最佳假设。 必须由零个或多个最终结果后接零个或多个中间结果组成。 在后续 SpeechRecognitionResultEvent 事件中,中间结果可能会被更新为新的中间结果或最终结果,或被移除(当处于 "results" 数组末尾且数组长度减少时)。 最终结果不得被覆盖或移除。 所有索引小于 resultIndex 的条目与上一次触发 SpeechRecognitionResultEvent 时的数组完全一致。 所有等于或大于 resultIndex 的条目(若存在)将会被新结果覆盖。 "results" 数组的长度可以增加或减少,但不得小于 resultIndex。 注意当 resultIndex 等于 results.length 时,不会返回新结果,这可能发生在数组长度减少以移除一个或多个中间结果的情形。

4.1.11. 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
当调用此构造函数时,执行如下步骤:
  1. 如果 boost 小于 0.0 或大于 10.0,抛出 SyntaxError 并中止这些步骤。

  2. 令 phr 为新建的 SpeechRecognitionPhrase 对象。

  3. 设置 phr.[[phrase]] 为 phrase 的值。

  4. 设置 phr.[[boost]] 为 boost 的值。

  5. 返回 phr。

phrase attribute, 类型为 DOMString,只读
该属性返回 [[phrase]] 的值。
boost attribute, 类型为 float,只读
该属性返回 [[boost]] 的值。

4.1.12. SpeechGrammar

SpeechGrammar 对象表示语法的容器。

语法支持已废弃并移除。grammar 对象仅为向后兼容保留,不影响语音识别。

此结构具有以下属性:

src attribute, 类型为 DOMString
必填的 src 属性是语法的 URI。
weight attribute, 类型为 float
可选的 weight 属性控制该语法的权重,默认为 1。 较大权重正向提升该语法,较小权重则降低其权重。

4.1.13. SpeechGrammarList

SpeechGrammarList 对象表示 SpeechGrammar 对象的合集。 该结构具有以下属性:

语法支持已废弃并移除。grammar 对象仅为向后兼容保留,不影响语音识别。

length attribute, 类型为 unsigned long,只读
length 属性表示当前数组中有多少个语法。
item(index) getter
item 获取器返回语法数组中索引为 index 的 SpeechGrammar;如果 index 大于或等于 length 属性的值,则返回 null。 用户代理必须确保 length 属性被设置为数组中的元素数量。 用户代理必须确保按索引从小到大排列的顺序与语法添加到数组中的顺序一致。
addFromURI(src, weight) 方法
该方法根据 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 charIndex = 0;
    unsigned long charLength = 0;
    float elapsedTime = 0;
    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。 具体来说,如果某个话语已经开始被朗读且尚未完成朗读。 这与全局 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() 时本属性为 getVoices() 返回的 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 孵化小组成员,以及创建本规范依据的最终报告。

一致性

文档约定

一致性要求通过描述性断言和 RFC 2119 术语结合表达。 本规范规范性部分中的关键词 “MUST”(必须)、“MUST NOT”(禁止)、“REQUIRED”(需要)、“SHALL”(应)、“SHALL NOT”(不应)、“SHOULD”(建议)、“SHOULD NOT”(不建议)、“RECOMMENDED”(推荐)、“MAY”(可以)、“OPTIONAL”(可选) 应当按照 RFC 2119 中的解释理解。 但为了可读性,本规范不会将这些单词全部大写。

除非明确标注为非规范性、示例和注释的部分,规范文档的所有文字均为规范内容。[RFC2119]

本规范中的示例以 “例如(for example)” 开头, 或通过 class="example" 属性与规范性文本区分, 如下所示:

这里是一个信息性示例。

信息性注释以 “注(Note)” 开头, 并通过 class="note" 属性与规范性文本区分, 如下所示:

注:这是一个信息性注释。

索引

本规范定义的术语

引用定义的术语

参考文献

规范性引用

[BCP47]
Addison Phillips; Mark Davis. 用于标识 语言的标签。2009 年 9 月。最佳当前实践。URL: https://www.rfc-editor.org/info/bcp47
[DOM]
Anne van Kesteren. DOM 标准。现行标准。 URL: https://dom.spec.whatwg.org/
[HTML]
Anne van Kesteren; 等。HTML 标准。 现行标准。URL: https://html.spec.whatwg.org/multipage/
[HTMLSPEECH]
Michael Bodell; 等。HTML 语音孵化器 小组最终报告。URL: https://www.w3.org/2005/Incubator/htmlspeech/XGR-htmlspeech-20111206/
[MEDIACAPTURE-STREAMS]
Cullen Jennings; 等。媒体捕获与 流。URL: https://w3c.github.io/mediacapture-main/
[PERMISSIONS]
Marcos Caceres; Mike Taylor. 权限。URL: https://w3c.github.io/permissions/
[PERMISSIONS-POLICY-1]
Ian Clelland; Ari Chivukula. 权限 策略。URL: https://w3c.github.io/webappsec-permissions-policy/
[RFC2119]
S. Bradner. 用于在 RFC 中 表示要求级别的关键词。1997 年 3 月。最佳当前实践。URL: https://datatracker.ietf.org/doc/html/rfc2119
[SERVICE-WORKERS]
Monica CHINTALA; Yoshisato Yanagisawa. Service Workers 每夜构建版。URL: https://w3c.github.io/ServiceWorker/
[SSML]
Daniel Burnett; Zhi Wei Shuang. 语音合成 标记语言(SSML)1.1 版。2010 年 9 月 7 日。推荐标准。URL: https://www.w3.org/TR/speech-synthesis11/
[STORAGE]
Anne van Kesteren。存储标准。现行标准。URL:https://storage.spec.whatwg.org/
[WEBIDL]
Edgar Chen; Timothy Gu. Web IDL 标准。现行 标准。URL: https://webidl.spec.whatwg.org/

IDL 索引

[SecureContext, Exposed=Window]
interface SpeechRecognition : EventTarget {
    constructor();

    // recognition parameters
    attribute SpeechGrammarList grammars;
    attribute DOMString lang;
    attribute boolean continuous;
    attribute boolean interimResults;
    attribute boolean unspokenPunctuation;
    attribute unsigned long maxAlternatives;
    attribute boolean processLocally;
    attribute ObservableArray<SpeechRecognitionPhrase> phrases;

    // methods to drive the speech interaction
    undefined start();
    undefined start(MediaStreamTrack audioTrack);
    undefined stop();
    undefined abort();
    static Promise<SpeechRecognitionAvailabilityStatus> available(SpeechRecognitionOptions options);
    static Promise<boolean> install(SpeechRecognitionOptions options);

    // event methods
    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;
};

enum SpeechRecognitionQuality {
  "command",
  "dictation",
  "conversation"
};

dictionary SpeechRecognitionOptions {
  required sequence<DOMString> langs;
  boolean processLocally = false;
  SpeechRecognitionQuality quality = "command";
};

enum SpeechRecognitionErrorCode {
    "no-speech",
    "aborted",
    "audio-capture",
    "network",
    "not-allowed",
    "service-not-allowed",
    "language-not-supported",
    "phrases-not-supported"
};

enum SpeechRecognitionAvailabilityStatus {
    "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 message = "";
};

// Item in N-best list
[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;
    readonly attribute double speechStartTime;
    readonly attribute double speechEndTime;
};

// A collection of responses (used in continuous mode)
[SecureContext, Exposed=Window]
interface SpeechRecognitionResultList {
    readonly attribute unsigned long length;
    getter SpeechRecognitionResult? item(unsigned long index);
};

// A full response, which could be interim or final, part of a continuous response or not
[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 resultIndex = 0;
    required SpeechRecognitionResultList results;
};

// The object representing a speech grammar. This interface has been deprecated and exists in this spec for the sole purpose of maintaining backwards compatibility.
[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 weight = 1.0);
    undefined addFromString(DOMString string,
                    optional float weight = 1.0);
};

// The object representing a phrase for contextual biasing.
[SecureContext, Exposed=Window]
interface SpeechRecognitionPhrase {
    constructor(DOMString phrase, optional float boost = 1.0);
    readonly attribute DOMString phrase;
    readonly attribute float boost;
};

[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 charIndex = 0;
    unsigned long charLength = 0;
    float elapsedTime = 0;
    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;
};

Issues Index

The group has discussed whether WebRTC might be used to specify selection of audio sources and remote recognizers. See Interacting with WebRTC, the Web Audio API and other external sources thread on public-speech-api@w3.org. ↵
The group has discussed whether confidence can be specified in a speech-recognition-engine-independent manner and whether confidence threshold and nomatch should be included, because this is not a dialog API. See Confidence property thread on public-speech-api@w3.org. ↵