├── .github ├── PULL_REQUEST_TEMPLATE.md └── workflows │ └── auto-publish.yml ├── .gitignore ├── .pr-preview.json ├── .travis.yml ├── Makefile ├── README.md ├── explainers └── on-device-speech-recognition.md ├── index.bs ├── package.json ├── ui-example.png └── w3c.json /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | Closes #??? 2 | 3 | The following tasks have been completed: 4 | 5 | * [ ] Updated web-platform-tests: (link to pull request) 6 | 7 | Implementation commitment: 8 | 9 | * [ ] Blink: (link to issue) 10 | * [ ] Gecko: (link to issue) 11 | * [ ] WebKit: (link to issue) 12 | 13 | -------------------------------------------------------------------------------- /.github/workflows/auto-publish.yml: -------------------------------------------------------------------------------- 1 | name: Auto-publish 2 | on: 3 | pull_request: {} 4 | push: 5 | paths: 6 | - index.bs 7 | branches: [main] 8 | 9 | jobs: 10 | main: 11 | name: Build, Validate and Deploy 12 | runs-on: ubuntu-latest 13 | steps: 14 | - uses: actions/checkout@v4 15 | - uses: w3c/spec-prod@v2 16 | with: 17 | GH_PAGES_BRANCH: gh-pages 18 | BUILD_FAIL_ON: link-error 19 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | index.html 2 | node_modules/ 3 | .DS_Store 4 | .idea/ 5 | 6 | -------------------------------------------------------------------------------- /.pr-preview.json: -------------------------------------------------------------------------------- 1 | { 2 | "src_file": "index.bs", 3 | "type": "bikeshed", 4 | "params": { 5 | "force": 1 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | branches: 2 | only: 3 | - master 4 | language: python 5 | python: 6 | - "3.8" 7 | install: 8 | - pip install bikeshed 9 | - bikeshed update 10 | script: 11 | - bikeshed spec 12 | before_deploy: 13 | - mkdir out 14 | - mv *.html *.png out/ 15 | deploy: 16 | local-dir: out 17 | provider: pages 18 | skip-cleanup: true 19 | github-token: $GITHUB_TOKEN 20 | keep-history: true 21 | on: 22 | branch: master 23 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | SHELL := /bin/bash 2 | 3 | DST := $(patsubst %.bs,%.html,$(wildcard *.bs)) 4 | REMOTE := $(filter remote,$(MAKECMDGOALS)) 5 | 6 | all: $(DST) 7 | @ echo "All done" 8 | 9 | %.html : %.bs node_modules/vnu-jar/build/dist/vnu.jar 10 | ifndef REMOTE 11 | @ echo "Building $@" 12 | bikeshed --die-on=warning spec $< $@ 13 | java -jar node_modules/vnu-jar/build/dist/vnu.jar --also-check-css $@ 14 | else 15 | @ echo "Building $@ remotely" 16 | @ (HTTP_STATUS=$$(curl https://api.csswg.org/bikeshed/ \ 17 | --output $@ \ 18 | --write-out "%{http_code}" \ 19 | --header "Accept: text/plain, text/html" \ 20 | -F die-on=warning \ 21 | -F file=@$<) && \ 22 | [[ "$$HTTP_STATUS" -eq "200" ]]) || ( \ 23 | echo ""; cat $@; echo ""; \ 24 | rm -f index.html; \ 25 | exit 22 \ 26 | ); 27 | endif 28 | 29 | node_modules/vnu-jar/build/dist/vnu.jar: 30 | npm install vnu-jar 31 | 32 | remote: all 33 | 34 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Web Speech API 2 | 3 | This is the source for the [Web Speech API](https://webaudio.github.io/web-speech-api/) spec. 4 | 5 | ## Tests 6 | 7 | For normative changes, a corresponding 8 | [web-platform-tests](https://github.com/w3c/web-platform-tests) PR is highly appreciated. Typically, 9 | both PRs will be merged at the same time. Note that a test change that contradicts the spec should 10 | not be merged before the corresponding spec change. If testing is not practical, please explain why 11 | and if appropriate [file a web-platform-tests issue](https://github.com/w3c/web-platform-tests/issues/new) 12 | to follow up later. Add the `type:untestable` or `type:missing-coverage` label as appropriate. 13 | -------------------------------------------------------------------------------- /explainers/on-device-speech-recognition.md: -------------------------------------------------------------------------------- 1 | # Explainer: On-Device Speech Recognition for the Web Speech API 2 | 3 | ## Introduction 4 | 5 | The Web Speech API is a powerful browser feature that enables applications to perform speech recognition. Traditionally, this functionality relies on sending audio data to cloud-based services for recognition. While this approach is effective, it has certain drawbacks: 6 | 7 | - **Privacy concerns:** Raw and transcribed audio is transmitted over the network. 8 | - **Latency issues:** Users may experience delays due to network communication. 9 | - **Offline limitations:** Speech recognition does not work without an internet connection. 10 | 11 | To address these issues, we introduce **on-device speech recognition capabilities** as part of the Web Speech API. This enhancement allows speech recognition to run locally on user devices, providing a faster, more private, and offline-compatible experience. 12 | 13 | ## Why Use On-Device Speech Recognition? 14 | 15 | ### 1. **Privacy** 16 | On-device processing ensures that neither raw audio nor transcriptions leave the user's device, enhancing data security and user trust. 17 | 18 | ### 2. **Performance** 19 | Local processing reduces latency, providing a smoother and faster user experience. 20 | 21 | ### 3. **Offline Functionality** 22 | Applications can offer speech recognition capabilities even without an active internet connection, increasing their utility in remote or low-connectivity environments. 23 | 24 | ## Example use cases 25 | ### 1. Company with data residency requirements 26 | Websites with strict data residency requirements (i.e., regulatory, legal, or company policy) can ensure that audio data remains on the user's device and is not sent over the network for processing. This is particularly crucial for compliance with regulations like GDPR, which considers voice as personally identifiable information (PII) as voice recordings can reveal information about an individual's gender, ethnic origin, or even potential health conditions. On-device processing significantly enhances user privacy by minimizing the exposure of sensitive voice data. 27 | 28 | ### 2. Video conferencing service with strict performance requirements (e.g. meet.google.com) 29 | Some websites would only adopt the Web Speech API if it meets strict performance requirements. On-device speech recognition may provide better accuracy and latency as well as provide additional features (e.g. contextual biasing) that may not be available by the cloud-based service used by the user agent. In the event on-device speech recognition is not available, these websites may elect to use an alternative cloud-based speech recognition provider that meet these requirements instead of the default one provided by the user agent. 30 | 31 | ### 3. Educational website (e.g. khanacademy.org) 32 | Applications that need to function in unreliable or offline network conditions—such as voice-based productivity tools, educational software, or accessibility features—benefit from on-device speech recognition. This enables uninterrupted functionality during flights, remote travel, or in areas with limited connectivity. When on-device recognition is unavailable, a website can choose to hide the UI or gracefully degrade functionality to maintain a coherent user experience. 33 | 34 | ## New Methods 35 | 36 | ### 1. `Promise availableOnDevice(DOMString lang)` 37 | This method checks if on-device speech recognition is available for a specific language. Developers can use this to determine whether to enable features that require on-device speech recognition. 38 | 39 | #### Example Usage 40 | ```javascript 41 | const lang = 'en-US'; 42 | SpeechRecognition.availableOnDevice(lang).then((available) => { 43 | if (available) { 44 | console.log(`On-device speech recognition is available for ${lang}.`); 45 | } else { 46 | console.log(`On-device speech recognition is not available for ${lang}.`); 47 | } 48 | }); 49 | ``` 50 | 51 | ### 2. `Promise installOnDevice(DOMString[] lang)` 52 | This method install the resources required for on-device speech recognition for the given BCP-47 language codes. The installation process may download and configure necessary language models. 53 | 54 | #### Example Usage 55 | ```javascript 56 | const lang = 'en-US'; 57 | SpeechRecognition.installOnDevice([lang]).then((success) => { 58 | if (success) { 59 | console.log('On-device speech recognition resources installed successfully.'); 60 | } else { 61 | console.error('Unable to install on-device speech recognition.'); 62 | } 63 | }); 64 | ``` 65 | 66 | ## New Attribute 67 | 68 | ### 1. `mode` attribute in the `SpeechRecognition` interface 69 | The `mode` attribute in the `SpeechRecognition` interface defines how speech recognition should behave when starting a session. 70 | 71 | #### `SpeechRecognitionMode` Enum 72 | 73 | - **"on-device-preferred"**: Use on-device speech recognition if available. If not, fall back to cloud-based speech recognition. 74 | - **"on-device-only"**: Only use on-device speech recognition. If it's unavailable, throw an error. 75 | 76 | #### Example Usage 77 | ```javascript 78 | const recognition = new SpeechRecognition(); 79 | recognition.mode = "ondevice-only"; // Only use on-device speech recognition. 80 | recognition.start(); 81 | ``` 82 | 83 | ## Privacy considerations 84 | To reduce the risk of fingerprinting, user agents must implementing privacy-preserving countermeasures. The Web Speech API will employ the same masking techniques used by the [Web Translation API](https://github.com/webmachinelearning/writing-assistance-apis/pull/47). 85 | 86 | ## Conclusion 87 | The addition of on-device speech recognition capabilities to the Web Speech API marks a significant step forward in creating more private, performant, and accessible web applications. By leveraging these new methods, developers can enhance user experiences while addressing key concerns around privacy and connectivity. -------------------------------------------------------------------------------- /index.bs: -------------------------------------------------------------------------------- 1 | 22 | 23 |
  24 | {
  25 |   "HTMLSPEECH": {
  26 |     "authors": [
  27 |       "Michael Bodell",
  28 |       "Björn Bringert",
  29 |       "Robert Brown",
  30 |       "Daniel C. Burnett",
  31 |       "Deborah Dahl",
  32 |       "Dan Druta",
  33 |       "Patrick Ehlen",
  34 |       "Charles Hemphill",
  35 |       "Michael Johnston",
  36 |       "Olli Pettay",
  37 |       "Satish Sampath",
  38 |       "Marc Schröder",
  39 |       "Glen Shires",
  40 |       "Raj Tumuluri",
  41 |       "Milan Young"
  42 |     ],
  43 |     "href": "https://www.w3.org/2005/Incubator/htmlspeech/XGR-htmlspeech-20111206/",
  44 |     "title": "HTML Speech Incubator Group Final Report"
  45 |   }
  46 | }
  47 | 
48 | 49 |

Introduction

50 | 51 |

This section is non-normative.

52 | 53 |

The Web Speech API aims to enable web developers to provide, in a web browser, speech-input and text-to-speech output features that are typically not available when using standard speech-recognition or screen-reader software. 54 | The API itself is agnostic of the underlying speech recognition and synthesis implementation and can support both server-based and client-based/embedded recognition and synthesis. 55 | The API is designed to enable both brief (one-shot) speech input and continuous speech input. 56 | Speech recognition results are provided to the web page as a list of hypotheses, along with other relevant information for each hypothesis.

57 | 58 |

This specification is a subset of the API defined in the [[HTMLSPEECH|HTML Speech Incubator Group Final Report]]. 59 | That report is entirely informative since it is not a standards track document. 60 | All portions of that report may be considered informative with regards to this document, and provide an informative background to this document. 61 | This specification is a fully-functional subset of that report. 62 | Specifically, this subset excludes the underlying transport protocol, the proposed additions to HTML markup, and it defines a simplified subset of the JavaScript API. 63 | This subset supports the majority of use-cases and sample code in the Incubator Group Final Report. 64 | This subset does not preclude future standardization of additions to the markup, API or underlying transport protocols, and indeed the Incubator Report defines a potential roadmap for such future work.

65 | 66 | 67 |

Use Cases

68 | 69 |

This section is non-normative.

70 | 71 |

This specification supports the following use cases, as defined in [[HTMLSPEECH#use-cases|Section 4 of the Incubator Report]].

72 | 73 | 89 | 90 |

To keep the API to a minimum, this specification does not directly support the following use case. 91 | This does not preclude adding support for this as a future API enhancement, and indeed the Incubator report provides a roadmap for doing so.

92 | 93 | 96 | 97 |

Security and privacy considerations

98 | 99 |
    100 |
  1. User agents must only start speech input sessions with explicit, informed user consent. 101 | User consent can include, for example: 102 |
      103 |
    • User click on a visible speech input element which has an obvious graphical representation showing that it will start speech input.
    • 104 |
    • Accepting a permission prompt shown as the result of a call to {{SpeechRecognition/start()}}.
    • 105 |
    • Consent previously granted to always allow speech input for this web page.
    • 106 |
    107 |
  2. 108 | 109 |
  3. User agents must give the user an obvious indication when audio is being recorded. 110 |
      111 |
    • In a graphical user agent, this could be a mandatory notification displayed by the user agent as part of its chrome and not accessible by the web page. 112 | This could for example be a pulsating/blinking record icon as part of the browser chrome/address bar, an indication in the status bar, an audible notification, or anything else relevant and accessible to the user. 113 | This UI element must also allow the user to stop recording.
      114 | Example UI recording notification.
    • 115 | 116 |
    • In a speech-only user agent, the indication may for example take the form of the system speaking the label of the speech input element, followed by a short beep.
    • 117 |
    118 |
  4. 119 | 120 |
  5. The user agent may also give the user a longer explanation the first time speech input is used, to let the user know what it is and how they can tune their privacy settings to disable speech recording if required.
  6. 121 | 122 |
  7. To mitigate the risk of fingerprinting, user agents MUST NOT personalize speech recognition when performing speech recognition on a {{MediaStreamTrack}}.
  8. 123 |
124 | 125 |

Implementation considerations

126 | 127 |

This section is non-normative.

128 | 129 |
    130 |
  1. Spoken password inputs can be problematic from a security perspective, but it is up to the user to decide if they want to speak their password.
  2. 131 | 132 |
  3. Speech input could potentially be used to eavesdrop on users. 133 | Malicious webpages could use tricks such as hiding the input element or otherwise making the user believe that it has stopped recording speech while continuing to do so. 134 | They could also potentially style the input element to appear as something else and trick the user into clicking them. 135 | An example of styling the file input element can be seen at https://www.quirksmode.org/dom/inputfile.html. 136 | The above recommendations are intended to reduce this risk of such attacks.
  4. 137 |
138 | 139 |

API Description

140 | 141 |

This section is normative.

142 | 143 |

The SpeechRecognition Interface

144 | 145 |

The speech recognition interface is the scripted web API for controlling a given recognition.

146 | The term "final result" indicates a {{SpeechRecognitionResult}} in which the {{SpeechRecognitionResult/isFinal}} attribute is true. 147 | The term "interim result" indicates a {{SpeechRecognitionResult}} in which the {{SpeechRecognitionResult/isFinal}} attribute is false. 148 | 149 | {{SpeechRecognition}} has the following internal slots: 150 | 151 |
152 | : [[started]] 153 | :: 154 | A boolean flag representing whether the speech recognition started. The initial value is false. 155 |
156 | 157 |
158 | : [[processLocally]] 159 | :: 160 | A boolean flag indicating whether recognition MUST be performed locally. The initial value is false. 161 |
162 | 163 |
164 | : [[phrases]] 165 | :: 166 | A {{SpeechRecognitionPhraseList}} representing a list of phrases for contextual biasing. The initial value is null. 167 |
168 | 169 | 170 | [SecureContext, Exposed=Window] 171 | interface SpeechRecognition : EventTarget { 172 | constructor(); 173 | 174 | // recognition parameters 175 | attribute DOMString lang; 176 | attribute boolean continuous; 177 | attribute boolean interimResults; 178 | attribute unsigned long maxAlternatives; 179 | attribute boolean processLocally; 180 | attribute SpeechRecognitionPhraseList phrases; 181 | 182 | // methods to drive the speech interaction 183 | undefined start(); 184 | undefined start(MediaStreamTrack audioTrack); 185 | undefined stop(); 186 | undefined abort(); 187 | static Promise<AvailabilityStatus> available(SpeechRecognitionOptions options); 188 | static Promise<boolean> install(SpeechRecognitionOptions options); 189 | 190 | // event methods 191 | attribute EventHandler onaudiostart; 192 | attribute EventHandler onsoundstart; 193 | attribute EventHandler onspeechstart; 194 | attribute EventHandler onspeechend; 195 | attribute EventHandler onsoundend; 196 | attribute EventHandler onaudioend; 197 | attribute EventHandler onresult; 198 | attribute EventHandler onnomatch; 199 | attribute EventHandler onerror; 200 | attribute EventHandler onstart; 201 | attribute EventHandler onend; 202 | }; 203 | 204 | dictionary SpeechRecognitionOptions { 205 | required sequence<DOMString> langs; 206 | boolean processLocally = false; 207 | }; 208 | 209 | enum SpeechRecognitionErrorCode { 210 | "no-speech", 211 | "aborted", 212 | "audio-capture", 213 | "network", 214 | "not-allowed", 215 | "service-not-allowed", 216 | "language-not-supported", 217 | "phrases-not-supported" 218 | }; 219 | 220 | enum AvailabilityStatus { 221 | "unavailable", 222 | "downloadable", 223 | "downloading", 224 | "available" 225 | }; 226 | 227 | [SecureContext, Exposed=Window] 228 | interface SpeechRecognitionErrorEvent : Event { 229 | constructor(DOMString type, SpeechRecognitionErrorEventInit eventInitDict); 230 | readonly attribute SpeechRecognitionErrorCode error; 231 | readonly attribute DOMString message; 232 | }; 233 | 234 | dictionary SpeechRecognitionErrorEventInit : EventInit { 235 | required SpeechRecognitionErrorCode error; 236 | DOMString message = ""; 237 | }; 238 | 239 | // Item in N-best list 240 | [SecureContext, Exposed=Window] 241 | interface SpeechRecognitionAlternative { 242 | readonly attribute DOMString transcript; 243 | readonly attribute float confidence; 244 | }; 245 | 246 | // A complete one-shot simple response 247 | [SecureContext, Exposed=Window] 248 | interface SpeechRecognitionResult { 249 | readonly attribute unsigned long length; 250 | getter SpeechRecognitionAlternative item(unsigned long index); 251 | readonly attribute boolean isFinal; 252 | }; 253 | 254 | // A collection of responses (used in continuous mode) 255 | [SecureContext, Exposed=Window] 256 | interface SpeechRecognitionResultList { 257 | readonly attribute unsigned long length; 258 | getter SpeechRecognitionResult item(unsigned long index); 259 | }; 260 | 261 | // A full response, which could be interim or final, part of a continuous response or not 262 | [SecureContext, Exposed=Window] 263 | interface SpeechRecognitionEvent : Event { 264 | constructor(DOMString type, SpeechRecognitionEventInit eventInitDict); 265 | readonly attribute unsigned long resultIndex; 266 | readonly attribute SpeechRecognitionResultList results; 267 | }; 268 | 269 | dictionary SpeechRecognitionEventInit : EventInit { 270 | unsigned long resultIndex = 0; 271 | required SpeechRecognitionResultList results; 272 | }; 273 | 274 | // The object representing a phrase for contextual biasing. 275 | [SecureContext, Exposed=Window] 276 | interface SpeechRecognitionPhrase { 277 | constructor(DOMString phrase, optional float boost = 1.0); 278 | readonly attribute DOMString phrase; 279 | readonly attribute float boost; 280 | }; 281 | 282 | // The object representing a list of phrases for contextual biasing. 283 | [SecureContext, Exposed=Window] 284 | interface SpeechRecognitionPhraseList { 285 | constructor(sequence<SpeechRecognitionPhrase> phrases); 286 | readonly attribute unsigned long length; 287 | SpeechRecognitionPhrase item(unsigned long index); 288 | undefined addItem(SpeechRecognitionPhrase item); 289 | undefined removeItem(unsigned long index); 290 | }; 291 | 292 | 293 |

SpeechRecognition Attributes

294 | 295 |
296 |
lang attribute
297 |
This attribute will set the language of the recognition for the request, using a valid BCP 47 language tag. [[!BCP47]] 298 | If unset it remains unset for getting in script, but will default to use the language of the html document root element and associated hierarchy. 299 | This default value is computed and used when the input request opens a connection to the recognition service.
300 | 301 |
continuous attribute
302 |
When the continuous attribute is set to false, the user agent must return no more than one final result in response to starting recognition, 303 | for example a single turn pattern of interaction. 304 | When the continuous attribute is set to true, the user agent must return zero or more final results representing multiple consecutive recognitions in response to starting recognition, 305 | for example a dictation. 306 | The default value must be false. Note, this attribute setting does not affect interim results.
307 | 308 |
interimResults attribute
309 |
Controls whether interim results are returned. 310 | When set to true, interim results should be returned. 311 | When set to false, interim results must not be returned. 312 | The default value must be false. Note, this attribute setting does not affect final results.
313 | 314 |
maxAlternatives attribute
315 |
This attribute will set the maximum number of {{SpeechRecognitionAlternative}}s per result. 316 | The default value is 1.
317 | 318 |
processLocally attribute
319 |
This attribute, when set to true, indicates a requirement that the speech recognition process MUST be performed locally on the user's device. 320 | If set to false, the user agent can choose between local and remote processing. 321 | The default value is false. 322 |
323 | 324 |
phrases attribute
325 |
326 | This attribute represents a list of phrases for contextual biasing. 327 |
328 |
329 | The getter steps are to return the value of {{SpeechRecognition/[[phrases]]}}. 330 |
331 |
332 | The setter steps are: 333 | 1. If the {{SpeechRecognitionPhraseList/length}} of the given value is greater than 0 and the system does not support contextual biasing, 334 | throw a {{SpeechRecognitionErrorEvent}} with the {{phrases-not-supported}} error code and abort these steps. 335 | 1. Set {{SpeechRecognition/[[phrases]]}} to the given value. 336 | 1. Send a copy of {{SpeechRecognition/[[phrases]]}} to the system for initializing or updating the phrases for contextual biasing implementation. 337 |
338 |
339 | 340 |

The group has discussed whether WebRTC might be used to specify selection of audio sources and remote recognizers. 341 | See Interacting with WebRTC, the Web Audio API and other external sources thread on public-speech-api@w3.org.

342 | 343 |

SpeechRecognition Methods

344 | 345 |
346 |
start() method
347 |
348 | Start the speech recognition process, directly from a microphone on the device. 349 | When invoked, run the following steps: 350 | 351 | 1. Let |requestMicrophonePermission| be a boolan variable set to to `true`. 352 | 1. Run the [=start session algorithm=] with |requestMicrophonePermission|. 353 |
354 | 355 |
start({{MediaStreamTrack}} audioTrack) method
356 |
357 | Start the speech recognition process, using a {{MediaStreamTrack}} 358 | When invoked, run the following steps: 359 | 360 | 1. Let |audioTrack| be the first argument. 361 | 1. If |audioTrack|'s {{MediaStreamTrack/kind}} attribute is NOT `"audio"`, 362 | throw an {{InvalidStateError}} and abort these steps. 363 | 1. If |audioTrack|'s {{MediaStreamTrack/readyState}} attribute is NOT 364 | `"live"`, throw an {{InvalidStateError}} and abort these steps. 365 | 1. Let |requestMicrophonePermission| be `false`. 366 | 1. Run the [=start session algorithm=] with |requestMicrophonePermission|. 367 |
368 | 369 |
stop() method
370 |
The stop method represents an instruction to the recognition service to stop listening to more audio, and to try and return a result using just the audio that it has already received for this recognition. 371 | A typical use of the stop method might be for a web application where the end user is doing the end pointing, similar to a walkie-talkie. 372 | The end user might press and hold the space bar to talk to the system and on the space down press the start call would have occurred and when the space bar is released the stop method is called to ensure that the system is no longer listening to the user. 373 | Once the stop method is called the speech service must not collect additional audio and must not continue to listen to the user. 374 | The speech service must attempt to return a recognition result (or a nomatch) based on the audio that it has already collected for this recognition. 375 | If the stop method is called on an object which is already stopped or being stopped (that is, start was never called on it, the end or error event has fired on it, or stop was previously called on it), the user agent must ignore the call.
376 | 377 |
abort() method
378 |
The abort method is a request to immediately stop listening and stop recognizing and do not return any information but that the system is done. 379 | When the abort method is called, the speech service must stop recognizing. 380 | The user agent must raise an end event once the speech service is no longer connected. 381 | If the abort method is called on an object which is already stopped or aborting (that is, start was never called on it, the end or error event has fired on it, or abort was previously called on it), the user agent must ignore the call.
382 | 383 |
available({{SpeechRecognitionOptions}} options) method
384 |
385 | The {{SpeechRecognition/available}} method returns a {{Promise}} that resolves to a {{AvailabilityStatus}} indicating the recognition availability matching the {{SpeechRecognitionOptions}} argument. 386 | 387 | When invoked, run these steps: 388 | 1. Let promise be a new promise. 389 | 1. Run the availability algorithm with options and promise. If it returns an exception, throw it and abort these steps. 390 | 1. Return promise. 391 |
392 | 393 |
install({{SpeechRecognitionOptions}} options) method
394 |
395 | The {{SpeechRecognition/install}} method attempts to install speech recognition language packs for all languages specified in `options.langs`. 396 | It returns a {{Promise}} that resolves to a {{boolean}}. 397 | The promise resolves to `true` when all installation attempts for requested and supported languages succeed (or the languages were already installed). 398 | The promise resolves to `false` if `options.langs` is empty, if not all of the requested languages are supported, or if any installation attempt for a supported language fails. 399 | 400 | When invoked, run these steps: 401 | 1. If the [=current settings object=]'s [=relevant global object=]'s [=associated Document=] is NOT [=fully active=], throw an {{InvalidStateError}} and abort these steps. 402 | 1. If any lang in {{SpeechRecognitionOptions/langs}} of options is not a valid [[!BCP47]] language tag, throw a {{SyntaxError}} and abort these steps. 403 | 1. If the on-device speech recognition language pack for any lang in {{SpeechRecognitionOptions/langs}} of options is unsupported, return a resolved {{Promise}} with false and skip the rest of these steps. 404 | 1. Let promise be a new promise. 405 | 1. For each lang in {{SpeechRecognitionOptions/langs}} of options, initiate the download of the on-device speech recognition language for lang. 406 |

407 | Note: The user agent can prompt the user for explicit permission to download the on-device speech recognition language pack. 408 |

409 | 1. [=Queue a task=] on the [=relevant global object=]'s [=task queue=] to run the following step: 410 | - When the download of all languages specified by {{SpeechRecognitionOptions/langs}} of options succeeds, resolve promise with true, otherwise resolve it with false. 411 |

412 | Note: The false resolution of the Promise does not indicate the specific cause of failure. User agents are encouraged to provide more detailed information about the failure in developer tools console messages. However, this detailed error information is not exposed to the script. 413 |

414 | 1. Return promise. 415 |

416 | {{SpeechRecognitionOptions/processLocally}} of options is not used in this algorithm. 417 |

418 |
419 | 420 |
421 | 422 |

AvailabilityStatus Enum Values

423 |

The {{AvailabilityStatus}} enum indicates the availability of speech recognition capabilities. Its values are:

424 |
425 |
"unavailable"
426 |
Indicates that speech recognition is not available for the specified language(s) and processing preference. 427 | If {{SpeechRecognitionOptions/processLocally}} of options is `true`, this means on-device recognition for the language is not supported by the user agent. 428 | If {{SpeechRecognitionOptions/processLocally}} of options is `false`, it means neither local nor remote recognition is available for at least one of the specified languages.
429 | 430 |
"downloadable"
431 |
Indicates that on-device speech recognition for the specified language(s) is supported by the user agent but not yet installed. It can potentially be installed using the {{SpeechRecognition/install()}} method. This status is primarily relevant when {{SpeechRecognitionOptions/processLocally}} of options is true.
432 | 433 |
"downloading"
434 |
Indicates that on-device speech recognition for the specified language(s) is currently in the process of being downloaded. This status is primarily relevant when {{SpeechRecognitionOptions/processLocally}} of options is true.
435 | 436 |
"available"
437 |
Indicates that speech recognition is available for all specified language(s) and the given processing preference. 438 | If {{SpeechRecognitionOptions/processLocally}} of options is true, this means on-device recognition is installed and ready. 439 | If {{SpeechRecognitionOptions/processLocally}} of options is false, it means recognition (which could be local or remote) is available.
440 |
441 | 442 |

When the availability algorithm with options and promise is invoked, the user agent MUST run the following steps: 443 | 1. If the [=current settings object=]'s [=relevant global object=]'s [=associated Document=] is NOT [=fully active=], throw an {{InvalidStateError}} and abort these steps. 444 | 1. Let langs be {{SpeechRecognitionOptions/langs}} of options. 445 | 1. If any lang in langs is not a valid [[!BCP47]] language tag, throw a {{SyntaxError}} and abort these steps. 446 | 1. If {{SpeechRecognitionOptions/processLocally}} of options is `false`: 447 | 1. If langs is an empty sequence, let status be {{AvailabilityStatus/unavailable}}. 448 | 1. Else if speech recognition (which may be remote) is available for all language in langs, let status be {{AvailabilityStatus/available}}. 449 | 1. Else, let status be {{AvailabilityStatus/unavailable}}. 450 | 1. If {{SpeechRecognitionOptions/processLocally}} of options is `true`: 451 |

    452 |
  1. If langs is an empty sequence, let status be {{AvailabilityStatus/unavailable}}.
  2. 453 |
  3. Else: 454 |
      455 |
    1. Let finalStatus be {{AvailabilityStatus/available}}.
    2. 456 |
    3. For each language in langs: 457 |
        458 |
      1. Let currentLanguageStatus.
      2. 459 |
      3. If on-device speech recognition for language is installed, set currentLanguageStatus to {{AvailabilityStatus/available}}.
      4. 460 |
      5. Else if on-device speech recognition for language is currently being downloaded, set currentLanguageStatus to {{AvailabilityStatus/downloading}}.
      6. 461 |
      7. Else if on-device speech recognition for language is supported by the user agent but not yet installed, set currentLanguageStatus to {{AvailabilityStatus/downloadable}}.
      8. 462 |
      9. Else (on-device speech recognition for language is not supported), set currentLanguageStatus to {{AvailabilityStatus/unavailable}}.
      10. 463 |
      11. If currentLanguageStatus comes after finalStatus in the ordered list `[{{AvailabilityStatus/available}}, {{AvailabilityStatus/downloading}}, {{AvailabilityStatus/downloadable}}, {{AvailabilityStatus/unavailable}}]`, set finalStatus to currentLanguageStatus.
      12. 464 |
      465 |
    4. 466 |
    5. Let status be finalStatus.
    6. 467 |
    468 |
  4. 469 |
470 | 1. [=Queue a task=] on the [=relevant global object=]'s [=task queue=] to run the following step: 471 | - Resolve promise with status. 472 | 473 | When the start session algorithm with 474 | |requestMicrophonePermission| is invoked, the user agent MUST run the 475 | following steps: 476 | 477 | 1. If the [=current settings object=]'s [=relevant global object=]'s 478 | [=associated Document=] is NOT [=fully active=], throw an {{InvalidStateError}} 479 | and abort these steps. 480 | 1. If {{SpeechRecognition/[[started]]}} is `true` and no error event or end event 482 | has fired on it, throw an {{InvalidStateError}} and abort these steps. 483 | 1. If this.{{SpeechRecognition/[[processLocally]]}} is `true`: 484 | 1. If the user agent determines that local speech recognition is not available for this.{{SpeechRecognition/lang}}, or if it cannot fulfill the local processing requirement for other reasons: 485 | 1. [=Queue a task=] to [=fire an event=] named error at [=this=] using {{SpeechRecognitionErrorEvent}} with its {{SpeechRecognitionErrorEvent/error}} attribute initialized to {{SpeechRecognitionErrorCode/service-not-allowed}} and its {{SpeechRecognitionErrorEvent/message}} attribute set to an implementation-defined string detailing the reason. 486 | 1. Abort these steps. 487 | 1. Set {{[[started]]}} to `true`. 488 | 1. If |requestMicrophonePermission| is `true` and [=request 489 | permission to use=] "`microphone`" is [=permission/"denied"=], abort 490 | these steps. 491 | 1. Once the system is successfully listening to the recognition, queue a task to 492 | [=fire an event=] named start at [=this=]. 493 | 494 |

SpeechRecognition Events

495 | 496 |

The DOM Level 2 Event Model is used for speech recognition events. 497 | The methods in the EventTarget interface should be used for registering event listeners. 498 | The SpeechRecognition interface also contains convenience attributes for registering a single event handler for each event type. 499 | These events do not bubble and are not cancelable.

500 | 501 |

For all these events, the timeStamp attribute defined in the DOM Level 2 Event interface must be set to the best possible estimate of when the real-world event which the event object represents occurred. 502 | This timestamp must be represented in the user agent's view of time, even for events where the timestamps in question could be raised on a different machine like a remote recognition service (i.e., in a speechend event with a remote speech endpointer).

503 | 504 |

Unless specified below, the ordering of the different events is undefined. 505 | For example, some implementations may fire audioend before speechstart or speechend if the audio detector is client-side and the speech detector is server-side.

506 | 507 |
508 |
audiostart event
509 |
Fired when the user agent has started to capture audio.
510 | 511 |
soundstart event
512 |
Fired when some sound, possibly speech, has been detected. 513 | This must be fired with low latency, e.g. by using a client-side energy detector. 514 | The audiostart event must always have been fired before the soundstart event.
515 | 516 |
speechstart event
517 |
Fired when the speech that will be used for speech recognition has started. 518 | The audiostart event must always have been fired before the speechstart event.
519 | 520 |
speechend event
521 |
Fired when the speech that will be used for speech recognition has ended. 522 | The speechstart event must always have been fired before speechend.
523 | 524 |
soundend event
525 |
Fired when some sound is no longer detected. 526 | This must be fired with low latency, e.g. by using a client-side energy detector. 527 | The soundstart event must always have been fired before soundend.
528 | 529 |
audioend event
530 |
Fired when the user agent has finished capturing audio. 531 | The audiostart event must always have been fired before audioend.
532 | 533 |
result event
534 |
Fired when the speech recognizer returns a result. 535 | The event must use the {{SpeechRecognitionEvent}} interface. 536 | The audiostart event must always have been fired before the result event.
537 | 538 |
nomatch event
539 |
Fired when the speech recognizer returns a final result with no recognition hypothesis that meet or exceed the confidence threshold. 540 | The event must use the {{SpeechRecognitionEvent}} interface. 541 | The {{SpeechRecognitionEvent/results}} attribute in the event may contain speech recognition results that are below the confidence threshold or may be null. 542 | The {{audiostart}} event must always have been fired before the nomatch event.
543 | 544 |
error event
545 |
Fired when a speech recognition error occurs. 546 | The event must use the {{SpeechRecognitionErrorEvent}} interface.
547 | 548 |
start event
549 |
Fired when the recognition service has begun to listen to the audio with the intention of recognizing. 550 | 551 |
end event
552 |
Fired when the service has disconnected. 553 | The event must always be generated when the session ends no matter the reason for the end.
554 |
555 | 556 |

SpeechRecognitionErrorEvent

557 | 558 |

The {{SpeechRecognitionErrorEvent}} interface is used for the error event.

559 |
560 |
error attribute
561 |
The errorCode is an enumeration indicating what has gone wrong. 562 | The values are: 563 |
564 |
"no-speech"
565 |
No speech was detected.
566 | 567 |
"aborted"
568 |
Speech input was aborted somehow, maybe by some user-agent-specific behavior such as UI that lets the user cancel speech input.
569 | 570 |
"audio-capture"
571 |
Audio capture failed.
572 | 573 |
"network"
574 |
Some network communication that was required to complete the recognition failed.
575 | 576 |
"not-allowed"
577 |
The user agent is not allowing any speech input to occur for reasons of security, privacy or user preference.
578 | 579 |
"service-not-allowed"
580 |
The user agent is not allowing the web application requested speech service, but would allow some speech service, to be used either because the user agent doesn't support the selected one or because of reasons of security, privacy or user preference.
581 | 582 |
"language-not-supported"
583 |
The language was not supported.
584 | 585 |
"phrases-not-supported"
586 |
The speech recognition model does not support phrases for contextual biasing.
587 |
588 |
589 | 590 |
message attribute
591 |
The message content is implementation specific. 592 | This attribute is primarily intended for debugging and developers should not use it directly in their application user interface.
593 |
594 | 595 |

SpeechRecognitionAlternative

596 | 597 |

The SpeechRecognitionAlternative represents a simple view of the response that gets used in a n-best list. 598 | 599 |

600 |
transcript attribute
601 |
The transcript string represents the raw words that the user spoke. 602 | For continuous recognition, leading or trailing whitespace MUST be included where necessary such that concatenation of consecutive SpeechRecognitionResults produces a proper transcript of the session.
603 | 604 |
confidence attribute
605 |
The confidence represents a numeric estimate between 0 and 1 of how confident the recognition system is that the recognition is correct. 606 | A higher number means the system is more confident. 607 |

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. 608 | See Confidence property thread on public-speech-api@w3.org.

609 |
610 | 611 |

SpeechRecognitionResult

612 | 613 |

The SpeechRecognitionResult object represents a single one-shot recognition match, either as one small part of a continuous recognition or as the complete return result of a non-continuous recognition.

614 | 615 |
616 |
length attribute
617 |
The long attribute represents how many n-best alternatives are represented in the item array.
618 | 619 |
item(index) getter
620 |
The item getter returns a SpeechRecognitionAlternative from the index into an array of n-best values. 621 | If index is greater than or equal to length, this returns null. 622 | The user agent must ensure that the length attribute is set to the number of elements in the array. 623 | The user agent must ensure that the n-best list is sorted in non-increasing confidence order (each element must be less than or equal to the confidence of the preceding elements).
624 | 625 |
isFinal attribute
626 |
The final boolean must be set to true if this is the final time the speech service will return this particular index value. 627 | If the value is false, then this represents an interim result that could still be changed.
628 |
629 | 630 |

SpeechRecognitionResultList

631 | 632 |

The SpeechRecognitionResultList object holds a sequence of recognition results representing the complete return result of a continuous recognition. 633 | For a non-continuous recognition it will hold only a single value.

634 | 635 |
636 |
length attribute
637 |
The length attribute indicates how many results are represented in the item array.
638 | 639 |
item(index) getter
640 |
The item getter returns a SpeechRecognitionResult from the index into an array of result values. 641 | If index is greater than or equal to length, this returns null. 642 | The user agent must ensure that the length attribute is set to the number of elements in the array.
643 |
644 | 645 |

SpeechRecognitionEvent

646 | 647 |

The SpeechRecognitionEvent is the event that is raised each time there are any changes to interim or final results.

648 | 649 |
650 |
resultIndex attribute
651 |
The resultIndex must be set to the lowest index in the "results" array that has changed.
652 | 653 |
results attribute
654 |
The array of all current recognition results for this session. 655 | Specifically all final results that have been returned, followed by the current best hypothesis for all interim results. 656 | It must consist of zero or more final results followed by zero or more interim results. 657 | On subsequent SpeechRecognitionResultEvent events, interim results may be overwritten by a newer interim result or by a final result or may be removed (when at the end of the "results" array and the array length decreases). 658 | Final results must not be overwritten or removed. 659 | All entries for indexes less than resultIndex must be identical to the array that was present when the last SpeechRecognitionResultEvent was raised. 660 | All array entries (if any) for indexes equal or greater than resultIndex that were present in the array when the last SpeechRecognitionResultEvent was raised are removed and overwritten with new results. 661 | The length of the "results" array may increase or decrease, but must not be less than resultIndex. 662 | Note that when resultIndex equals results.length, no new results are returned, this may occur when the array length decreases to remove one or more interim results.
663 |
664 | 665 |

SpeechRecognitionPhrase

666 | 667 |

The SpeechRecognitionPhrase object represents a phrase for contextual biasing and has the following internal slots:

668 | 669 |
670 | : [[phrase]] 671 | :: 672 | A {{DOMString}} representing the text string to be boosted. The initial value is null. 673 | An empty value is allowed but should be ignored by the speech recognition model. 674 |
675 | 676 |
677 | : [[boost]] 678 | :: 679 | A float representing approximately the natural log of the number of times more likely the website thinks this phrase is 680 | than what the speech recognition model knows. 681 | A valid boost must be a float value inside the range [0.0, 10.0], with a default value of 1.0 if not specified. 682 | A boost of 0.0 means the phrase is not boosted at all, and a higher boost means the phrase is more likely to appear. 683 | A boost of 10.0 means the phrase is extremely likely to appear and should be rarely set. 684 |
685 | 686 |
687 |
SpeechRecognitionPhrase(|phrase|, |boost|) constructor
688 |
689 | When this constructor is invoked, run the following steps: 690 | 1. If |boost| is smaller than 0.0 or greater than 10.0, throw a {{SyntaxError}} and abort these steps. 691 | 1. Let |phr| be a new object of type {{SpeechRecognitionPhrase}}. 692 | 1. Set |phr|.{{[[phrase]]}} to be the value of |phrase|. 693 | 1. Set |phr|.{{[[boost]]}} to be the value of |boost|. 694 | 1. Return |phr|. 695 |
696 | 697 |
phrase attribute
698 |
This attribute returns the value of {{[[phrase]]}}.
699 | 700 |
boost attribute
701 |
This attribute returns the value of {{[[boost]]}}.
702 |
703 | 704 |

SpeechRecognitionPhraseList

705 | 706 |

The SpeechRecognitionPhraseList object holds a list of phrases for contextual biasing and has the following internal slot:

707 | 708 |
709 | : [[phrases]] 710 | :: 711 | A list of {{SpeechRecognitionPhrase}} representing the phrases to be boosted. The initial value is an empty list. 712 |
713 | 714 |
715 |
SpeechRecognitionPhraseList(|phrases|) constructor
716 |
717 | When this constructor is invoked, run the following steps: 718 | 1. Let |list| be a new object of type {{SpeechRecognitionPhraseList}}. 719 | 1. Set |list|.{{SpeechRecognitionPhraseList/[[phrases]]}} to be the value of |phrases|. 720 | 1. Return |list|. 721 |
722 | 723 |
length attribute
724 |
725 | This attribute indicates the number of phrases in the list. 726 | When invoked, return the number of items in {{SpeechRecognitionPhraseList/[[phrases]]}}. 727 |
728 | 729 |
item(|index|) method
730 |
731 | This method gets the {{SpeechRecognitionPhrase}} object at the |index| of the list. 732 | When invoked, run the following steps: 733 | 1. If |index| is smaller than 0, or greater than or equal to {{SpeechRecognitionPhraseList/length}}, 734 | throw a {{RangeError}} and abort these steps. 735 | 1. Return the {{SpeechRecognitionPhrase}} at the |index| of {{SpeechRecognitionPhraseList/[[phrases]]}}. 736 |
737 | 738 |
addItem(|item|) method
739 |
740 | This method adds the {{SpeechRecognitionPhrase}} object |item| to the list. 741 | When invoked, add |item| to the end of {{SpeechRecognitionPhraseList/[[phrases]]}}. 742 | The list is allowed to have multiple {{SpeechRecognitionPhrase}} objects with the same {{SpeechRecognitionPhrase/[[phrase]]}} value, 743 | and the speech recognition model should use the last {{SpeechRecognitionPhrase/[[boost]]}} value 744 | for this {{SpeechRecognitionPhrase/[[phrase]]}} in the list. 745 |
746 | 747 |
removeItem(|index|) method
748 |
749 | This method removes the {{SpeechRecognitionPhrase}} object at the |index| of the list. 750 | When invoked, run the following steps: 751 | 1. If |index| is smaller than 0, or greater than or equal to {{SpeechRecognitionPhraseList/length}}, 752 | throw a {{RangeError}} and abort these steps. 753 | 1. Remove the {{SpeechRecognitionPhrase}} object at the |index| of {{SpeechRecognitionPhraseList/[[phrases]]}}. 754 |
755 |
756 | 757 |

The SpeechSynthesis Interface

758 | 759 |

The SpeechSynthesis interface is the scripted web API for controlling a text-to-speech output.

760 | 761 |
 762 | [Exposed=Window]
 763 | interface SpeechSynthesis : EventTarget {
 764 |     readonly attribute boolean pending;
 765 |     readonly attribute boolean speaking;
 766 |     readonly attribute boolean paused;
 767 | 
 768 |     attribute EventHandler onvoiceschanged;
 769 | 
 770 |     undefined speak(SpeechSynthesisUtterance utterance);
 771 |     undefined cancel();
 772 |     undefined pause();
 773 |     undefined resume();
 774 |     sequence<SpeechSynthesisVoice> getVoices();
 775 | };
 776 | 
 777 | partial interface Window {
 778 |     [SameObject] readonly attribute SpeechSynthesis speechSynthesis;
 779 | };
 780 | 
 781 | [Exposed=Window]
 782 | interface SpeechSynthesisUtterance : EventTarget {
 783 |     constructor(optional DOMString text);
 784 | 
 785 |     attribute DOMString text;
 786 |     attribute DOMString lang;
 787 |     attribute SpeechSynthesisVoice? voice;
 788 |     attribute float volume;
 789 |     attribute float rate;
 790 |     attribute float pitch;
 791 | 
 792 |     attribute EventHandler onstart;
 793 |     attribute EventHandler onend;
 794 |     attribute EventHandler onerror;
 795 |     attribute EventHandler onpause;
 796 |     attribute EventHandler onresume;
 797 |     attribute EventHandler onmark;
 798 |     attribute EventHandler onboundary;
 799 | };
 800 | 
 801 | [Exposed=Window]
 802 | interface SpeechSynthesisEvent : Event {
 803 |     constructor(DOMString type, SpeechSynthesisEventInit eventInitDict);
 804 |     readonly attribute SpeechSynthesisUtterance utterance;
 805 |     readonly attribute unsigned long charIndex;
 806 |     readonly attribute unsigned long charLength;
 807 |     readonly attribute float elapsedTime;
 808 |     readonly attribute DOMString name;
 809 | };
 810 | 
 811 | dictionary SpeechSynthesisEventInit : EventInit {
 812 |     required SpeechSynthesisUtterance utterance;
 813 |     unsigned long charIndex = 0;
 814 |     unsigned long charLength = 0;
 815 |     float elapsedTime = 0;
 816 |     DOMString name = "";
 817 | };
 818 | 
 819 | enum SpeechSynthesisErrorCode {
 820 |     "canceled",
 821 |     "interrupted",
 822 |     "audio-busy",
 823 |     "audio-hardware",
 824 |     "network",
 825 |     "synthesis-unavailable",
 826 |     "synthesis-failed",
 827 |     "language-unavailable",
 828 |     "voice-unavailable",
 829 |     "text-too-long",
 830 |     "invalid-argument",
 831 |     "not-allowed",
 832 | };
 833 | 
 834 | [Exposed=Window]
 835 | interface SpeechSynthesisErrorEvent : SpeechSynthesisEvent {
 836 |     constructor(DOMString type, SpeechSynthesisErrorEventInit eventInitDict);
 837 |     readonly attribute SpeechSynthesisErrorCode error;
 838 | };
 839 | 
 840 | dictionary SpeechSynthesisErrorEventInit : SpeechSynthesisEventInit {
 841 |     required SpeechSynthesisErrorCode error;
 842 | };
 843 | 
 844 | [Exposed=Window]
 845 | interface SpeechSynthesisVoice {
 846 |     readonly attribute DOMString voiceURI;
 847 |     readonly attribute DOMString name;
 848 |     readonly attribute DOMString lang;
 849 |     readonly attribute boolean localService;
 850 |     readonly attribute boolean default;
 851 | };
 852 | 
853 | 854 |

SpeechSynthesis Attributes

855 | 856 |
857 |
pending attribute
858 |
This attribute is true if the queue for the global SpeechSynthesis instance contains any utterances which have not started speaking.
859 | 860 |
speaking attribute
861 |
This attribute is true if an utterance is being spoken. 862 | Specifically if an utterance has begun being spoken and has not completed being spoken. 863 | This is independent of whether the global SpeechSynthesis instance is in the paused state.
864 | 865 |
paused attribute
866 |
This attribute is true when the global SpeechSynthesis instance is in the paused state. 867 | This state is independent of whether anything is in the queue. 868 | The default state of a the global SpeechSynthesis instance for a new window is the non-paused state.
869 |
870 | 871 |

SpeechSynthesis Methods

872 | 873 |
874 |
speak(utterance) method
875 |
This method appends the SpeechSynthesisUtterance object utterance to the end of the queue for the global SpeechSynthesis instance. 876 | It does not change the paused state of the SpeechSynthesis instance. 877 | If the SpeechSynthesis instance is paused, it remains paused. 878 | If it is not paused and no other utterances are in the queue, then this utterance is spoken immediately, 879 | else this utterance is queued to begin speaking after the other utterances in the queue have been spoken. 880 | If changes are made to the SpeechSynthesisUtterance object after calling this method and prior to the corresponding end or error event, 881 | it is not defined whether those changes will affect what is spoken, and those changes may cause an error to be returned. 882 | The SpeechSynthesis object takes exclusive ownership of the SpeechSynthesisUtterance object. 883 | Passing it as a speak() argument to another SpeechSynthesis object should throw an exception. 884 | (For example, two frames may have the same origin and each will contain a SpeechSynthesis object.)
885 | 886 |
cancel() method
887 |
This method removes all utterances from the queue. 888 | If an utterance is being spoken, speaking ceases immediately. 889 | This method does not change the paused state of the global SpeechSynthesis instance.
890 | 891 |
pause() method
892 |
This method puts the global SpeechSynthesis instance into the paused state. 893 | If an utterance was being spoken, it pauses mid-utterance. 894 | (If called when the SpeechSynthesis instance was already in the paused state, it does nothing.)
895 | 896 |
resume() method
897 |
This method puts the global SpeechSynthesis instance into the non-paused state. 898 | If an utterance was speaking, it continues speaking the utterance at the point at which it was paused, else it begins speaking the next utterance in the queue (if any). 899 | (If called when the SpeechSynthesis instance was already in the non-paused state, it does nothing.)
900 | 901 |
getVoices() method
902 |
This method returns the available voices. 903 | It is user agent dependent which voices are available. 904 | If there are no voices available, or if the the list of available voices is not yet known (for example: server-side synthesis where the list is determined asynchronously), 905 | then this method must return a SpeechSynthesisVoiceList of length zero.
906 |
907 | 908 |

SpeechSynthesis Events

909 | 910 |
911 |
voiceschanged event
912 |
Fired when the contents of the SpeechSynthesisVoiceList, that the getVoices method will return, have changed. 913 | Examples include: server-side synthesis where the list is determined asynchronously, or when client-side voices are installed/uninstalled.
914 |
915 | 916 |

SpeechSynthesisUtterance Attributes

917 | 918 |
919 |
text attribute
920 |
This attribute specifies the text to be synthesized and spoken for this utterance. 921 | This may be either plain text or a complete, well-formed SSML document. [[!SSML]] 922 | For speech synthesis engines that do not support SSML, or only support certain tags, the user agent or speech engine must strip away the tags they do not support and speak the text. 923 | There may be a maximum length of the text, it may be limited to 32,767 characters.
924 | 925 |
lang attribute
926 |
This attribute specifies the language of the speech synthesis for the utterance, using a valid BCP 47 language tag. [[!BCP47]] 927 | If unset it remains unset for getting in script, but will default to use the language of the html document root element and associated hierarchy. 928 | This default value is computed and used when the input request opens a connection to the recognition service.
929 | 930 |
voice attribute
931 |
This attribute specifies the speech synthesis voice that the web application wishes to use. 932 | When a {{SpeechSynthesisUtterance}} object is created this attribute must be initialized to null. 933 | If, at the time of the {{speak()}} method call, this attribute has been set to one of the {{SpeechSynthesisVoice}} objects returned by {{getVoices()}}, then the user agent must use that voice. 934 | If this attribute is unset or null at the time of the {{speak()}} method call, then the user agent must use a user agent default voice. 935 | The user agent default voice should support the current language (see {{SpeechSynthesisUtterance/lang}}) and can be a local or remote speech service and can incorporate end user choices via interfaces provided by the user agent such as browser configuration parameters. 936 |
937 | 938 |
volume attribute
939 |
This attribute specifies the speaking volume for the utterance. 940 | It ranges between 0 and 1 inclusive, with 0 being the lowest volume and 1 the highest volume, with a default of 1. 941 | If SSML is used, this value will be overridden by prosody tags in the markup.
942 | 943 |
rate attribute
944 |
This attribute specifies the speaking rate for the utterance. 945 | It is relative to the default rate for this voice. 946 | 1 is the default rate supported by the speech synthesis engine or specific voice (which should correspond to a normal speaking rate). 947 | 2 is twice as fast, and 0.5 is half as fast. 948 | Values below 0.1 or above 10 are strictly disallowed, but speech synthesis engines or specific voices may constrain the minimum and maximum rates further, for example, a particular voice may not actually speak faster than 3 times normal even if you specify a value larger than 3. 949 | If SSML is used, this value will be overridden by prosody tags in the markup.
950 | 951 |
pitch attribute
952 |
This attribute specifies the speaking pitch for the utterance. 953 | It ranges between 0 and 2 inclusive, with 0 being the lowest pitch and 2 the highest pitch. 954 | 1 corresponds to the default pitch of the speech synthesis engine or specific voice. 955 | Speech synthesis engines or voices may constrain the minimum and maximum rates further. 956 | If SSML is used, this value will be overridden by prosody tags in the markup.
957 |
958 | 959 |

SpeechSynthesisUtterance Events

960 | 961 | Each of these events must use the {{SpeechSynthesisEvent}} interface, 962 | except the error event which must use the {{SpeechSynthesisErrorEvent}} interface. 963 | These events do not bubble and are not cancelable. 964 | 965 |
966 |
start event
967 |
Fired when this utterance has begun to be spoken.
968 | 969 |
end event
970 |
Fired when this utterance has completed being spoken. 971 | If this event fires, the error event must not be fired for this utterance.
972 | 973 |
error event
974 |
Fired if there was an error that prevented successful speaking of this utterance. 975 | If this event fires, the end event must not be fired for this utterance.
976 | 977 |
pause event
978 |
Fired when and if this utterance is paused mid-utterance.
979 | 980 |
resume event
981 |
Fired when and if this utterance is resumed after being paused mid-utterance. 982 | Adding the utterance to the queue while the global SpeechSynthesis instance is in the paused state, and then calling the resume method 983 | does not cause the resume event to be fired, in this case the utterance's start event will be called when the utterance starts.
984 | 985 |
mark event
986 |
Fired when the spoken utterance reaches a named "mark" tag in SSML. [[!SSML]] 987 | The user agent must fire this event if the speech synthesis engine provides the event.
988 | 989 |
boundary event
990 |
Fired when the spoken utterance reaches a word or sentence boundary. 991 | The user agent must fire this event if the speech synthesis engine provides the event.
992 |
993 | 994 |

SpeechSynthesisEvent Attributes

995 | 996 |
997 |
utterance attribute
998 |
This attribute contains the SpeechSynthesisUtterance that triggered this event.
999 | 1000 |
charIndex attribute
1001 |
This attribute indicates the zero-based character index into the original utterance string that most closely approximates the current speaking position of the speech engine. 1002 | No guarantee is given as to where charIndex will be with respect to word boundaries (such as at the end of the previous word or the beginning of the next word), only that all text before charIndex has already been spoken, and all text after charIndex has not yet been spoken. 1003 | The user agent must return this value if the speech synthesis engine supports it, otherwise the user agent must return 0.
1004 | 1005 |
charLength attribute
1006 |
This attribute indicates the length of the text (word or sentence) that will be spoken corresponding to this event. 1007 | This attribute is the length, in characters, starting from this event's {{SpeechSynthesisEvent/charIndex}}. 1008 | The user agent must return this value if the speech synthesis engine supports it or the user agent can otherwise determine it, otherwise the user agent must return 0.
1009 | 1010 |
elapsedTime attribute
1011 |
This attribute indicates the time, in seconds, that this event triggered, relative to when this utterance has begun to be spoken. 1012 | The user agent must return this value if the speech synthesis engine supports it or the user agent can otherwise determine it, otherwise the user agent must return 0.
1013 | 1014 |
name attribute
1015 |
For mark events, this attribute indicates the name of the marker, as defined in SSML as the name attribute of a mark element. [[!SSML]] 1016 | For boundary events, this attribute indicates the type of boundary that caused the event: "word" or "sentence". 1017 | For all other events, this value should return "".
1018 |
1019 | 1020 |

SpeechSynthesisErrorEvent Attributes

1021 | 1022 |

The SpeechSynthesisErrorEvent is the interface used for the SpeechSynthesisUtterance error event.

1023 |
1024 |
error attribute
1025 |
The errorCode is an enumeration indicating what has gone wrong. 1026 | The values are: 1027 |
1028 |
"canceled"
1029 |
A cancel method call caused the SpeechSynthesisUtterance to be removed from the queue before it had begun being spoken.
1030 | 1031 |
"interrupted"
1032 |
A cancel method call caused the SpeechSynthesisUtterance to be interrupted after it has begun being spoken and before it completed.
1033 | 1034 |
"audio-busy"
1035 |
The operation cannot be completed at this time because the user-agent cannot access the audio output device. 1036 | (For example, the user may need to correct this by closing another application.)
1037 | 1038 |
"audio-hardware"
1039 |
The operation cannot be completed at this time because the user-agent cannot identify an audio output device. 1040 | (For example, the user may need to connect a speaker or configure system settings.)
1041 | 1042 |
"network"
1043 |
The operation cannot be completed at this time because some required network communication failed.
1044 | 1045 |
"synthesis-unavailable"
1046 |
The operation cannot be completed at this time because no synthesis engine is available. 1047 | (For example, the user may need to install or configure a synthesis engine.)
1048 | 1049 |
"synthesis-failed"
1050 |
The operation failed because synthesis engine had an error.
1051 | 1052 |
"language-unavailable"
1053 |
No appropriate voice is available for the language designated in SpeechSynthesisUtterance lang.
1054 | 1055 |
"voice-unavailable"
1056 |
The voice designated in SpeechSynthesisUtterance voice attribute is not available.
1057 | 1058 |
"text-too-long"
1059 |
The contents of the SpeechSynthesisUtterance text attribute is too long to synthesize.
1060 | 1061 |
"invalid-argument"
1062 |
The contents of the SpeechSynthesisUtterance rate, pitch or volume attribute is not supported by synthesizer.
1063 | 1064 |
"not-allowed"
1065 |
Synthesis was not allowed to start by the user agent or system in the current context.
1066 |
1067 |
1068 |
1069 | 1070 |

SpeechSynthesisVoice Attributes

1071 | 1072 |
1073 |
voiceURI attribute
1074 |
The voiceURI attribute specifies the speech synthesis voice and the location of the speech synthesis service for this voice. 1075 | Note that the voiceURI is a generic URI and can thus point to local or remote services, either through use of a URN with meaning to the user agent or by specifying a URL that the user agent recognizes as a local service.
1076 | 1077 |
name attribute
1078 |
This attribute is a human-readable name that represents the voice. 1079 | There is no guarantee that all names returned are unique.
1080 | 1081 |
lang attribute
1082 |
This attribute is a BCP 47 language tag indicating the language of the voice. [[!BCP47]]
1083 | 1084 |
localService attribute
1085 |
This attribute is true for voices supplied by a local speech synthesizer, and is false for voices supplied by a remote speech synthesizer service. 1086 | (This may be useful because remote services may imply additional latency, bandwidth or cost, whereas local voices may imply lower quality, however there is no guarantee that any of these implications are true.)
1087 | 1088 |
default attribute
1089 |
This attribute is true for at most one voice per language. 1090 | There may be a different default for each language. 1091 | It is user agent dependent how default voices are determined.
1092 |
1093 | 1094 |

Examples

1095 | 1096 |

This section is non-normative.

1097 | 1098 |

Speech Recognition Examples

1099 | 1100 |
1101 |

Using speech recognition to fill an input-field and perform a web search.

1102 | 1103 |
1104 |     <script type="text/javascript">
1105 |       var recognition = new SpeechRecognition();
1106 |       recognition.onresult = function(event) {
1107 |         if (event.results.length > 0) {
1108 |           q.value = event.results[0][0].transcript;
1109 |           q.form.submit();
1110 |         }
1111 |       }
1112 |     </script>
1113 | 
1114 |     <form action="https://www.example.com/search">
1115 |       <input type="search" id="q" name="q" size=60>
1116 |       <input type="button" value="Click to Speak" onclick="recognition.start()">
1117 |     </form>
1118 |   
1119 |
1120 | 1121 |
1122 |

Using speech recognition to fill an options list with alternative speech results.

1123 | 1124 |
1125 |     <script type="text/javascript">
1126 |       var recognition = new SpeechRecognition();
1127 |       recognition.maxAlternatives = 10;
1128 |       recognition.onresult = function(event) {
1129 |         if (event.results.length > 0) {
1130 |           var result = event.results[0];
1131 |           for (var i = 0; i < result.length; ++i) {
1132 |             var text = result[i].transcript;
1133 |             select.options[i] = new Option(text, text);
1134 |           }
1135 |         }
1136 |       }
1137 | 
1138 |       function start() {
1139 |         select.options.length = 0;
1140 |         recognition.start();
1141 |       }
1142 |     </script>
1143 | 
1144 |     <select id="select"></select>
1145 |     <button onclick="start()">Click to Speak</button>
1146 |   
1147 |
1148 | 1149 |
1150 |

Using continuous speech recognition to fill a textarea.

1151 | 1152 |
1153 |     <textarea id="textarea" rows=10 cols=80></textarea>
1154 |     <button id="button" onclick="toggleStartStop()"></button>
1155 | 
1156 |     <script type="text/javascript">
1157 |       var recognizing;
1158 |       var recognition = new SpeechRecognition();
1159 |       recognition.continuous = true;
1160 |       reset();
1161 |       recognition.onend = reset;
1162 | 
1163 |       recognition.onresult = function (event) {
1164 |         for (var i = event.resultIndex; i < event.results.length; ++i) {
1165 |           if (event.results[i].isFinal) {
1166 |             textarea.value += event.results[i][0].transcript;
1167 |           }
1168 |         }
1169 |       }
1170 | 
1171 |       function reset() {
1172 |         recognizing = false;
1173 |         button.innerHTML = "Click to Speak";
1174 |       }
1175 | 
1176 |       function toggleStartStop() {
1177 |         if (recognizing) {
1178 |           recognition.stop();
1179 |           reset();
1180 |         } else {
1181 |           recognition.start();
1182 |           recognizing = true;
1183 |           button.innerHTML = "Click to Stop";
1184 |         }
1185 |       }
1186 |     </script>
1187 |   
1188 |
1189 | 1190 |
1191 |

Using continuous speech recognition, showing final results in black and interim results in grey.

1192 | 1193 |
1194 |     <button id="button" onclick="toggleStartStop()"></button>
1195 |     <div style="border:dotted;padding:10px">
1196 |       <span id="final_span"></span>
1197 |       <span id="interim_span" style="color:grey"></span>
1198 |     </div>
1199 | 
1200 |     <script type="text/javascript">
1201 |       var recognizing;
1202 |       var recognition = new SpeechRecognition();
1203 |       recognition.continuous = true;
1204 |       recognition.interimResults = true;
1205 |       reset();
1206 |       recognition.onend = reset;
1207 | 
1208 |       recognition.onresult = function (event) {
1209 |         var final = "";
1210 |         var interim = "";
1211 |         for (var i = 0; i < event.results.length; ++i) {
1212 |           if (event.results[i].isFinal) {
1213 |             final += event.results[i][0].transcript;
1214 |           } else {
1215 |             interim += event.results[i][0].transcript;
1216 |           }
1217 |         }
1218 |         final_span.innerHTML = final;
1219 |         interim_span.innerHTML = interim;
1220 |       }
1221 | 
1222 |       function reset() {
1223 |         recognizing = false;
1224 |         button.innerHTML = "Click to Speak";
1225 |       }
1226 | 
1227 |       function toggleStartStop() {
1228 |         if (recognizing) {
1229 |           recognition.stop();
1230 |           reset();
1231 |         } else {
1232 |           recognition.start();
1233 |           recognizing = true;
1234 |           button.innerHTML = "Click to Stop";
1235 |           final_span.innerHTML = "";
1236 |           interim_span.innerHTML = "";
1237 |         }
1238 |       }
1239 |     </script>
1240 |   
1241 |
1242 | 1243 |

Speech Synthesis Examples

1244 | 1245 |
1246 |

Spoken text.

1247 | 1248 |
1249 |     <script type="text/javascript">
1250 |       speechSynthesis.speak(new SpeechSynthesisUtterance('Hello World'));
1251 |     </script>
1252 |   
1253 |
1254 | 1255 |
1256 |

Spoken text with attributes and events.

1257 | 1258 |
1259 |     <script type="text/javascript">
1260 |       var u = new SpeechSynthesisUtterance();
1261 |       u.text = 'Hello World';
1262 |       u.lang = 'en-US';
1263 |       u.rate = 1.2;
1264 |       u.onend = function(event) { alert('Finished in ' + event.elapsedTime + ' seconds.'); }
1265 |       speechSynthesis.speak(u);
1266 |     </script>
1267 |   
1268 |
1269 | 1270 |

Acknowledgments

1271 | 1272 |

1273 | Adam Sobieski (Phoster) 1274 | Björn Bringert (Google) 1275 | Charles Pritchard 1276 | Dominic Mazzoni (Google) 1277 | Gerardo Capiel (Benetech) 1278 | Jerry Carter 1279 | Kagami Sascha Rosylight 1280 | Marcos Cáceres (Mozilla) 1281 | Nagesh Kharidi (Openstream) 1282 | Olli Pettay (Mozilla) 1283 | Peter Beverloo (Google) 1284 | Raj Tumuluri (Openstream) 1285 | Satish Sampath (Google) 1286 |

1287 | 1288 |

Also, the members of the HTML Speech Incubator Group, and the corresponding [[HTMLSPEECH|Final Report]], which created the basis for this specification.

1289 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "web-speech-api", 3 | "version": "1.0.0", 4 | "description": "This is the source for the [Web Speech API](https://webaudio.github.io/web-speech-api/) spec.", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "repository": { 10 | "type": "git", 11 | "url": "git+https://github.com/WebAudio/web-speech-api.git" 12 | }, 13 | "bugs": { 14 | "url": "https://github.com/WebAudio/web-speech-api/issues" 15 | }, 16 | "homepage": "https://github.com/WebAudio/web-speech-api#readme", 17 | "devDependencies": { 18 | "vnu-jar": "^24.10.17" 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /ui-example.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WebAudio/web-speech-api/0f9acb03e5368c4781c66d9e01b366743ef76e5e/ui-example.png -------------------------------------------------------------------------------- /w3c.json: -------------------------------------------------------------------------------- 1 | { 2 | "group": "cg/audio-comgp", 3 | "contacts": ["svgeesus"], 4 | "repo-type": "cg-report" 5 | } 6 | --------------------------------------------------------------------------------