W3C

Speech JavaScript API Specification

Editor's Draft: 7 March 2012

Editors:
Bjorn Bringert, Google Inc.
Satish Sampath, Google Inc.
Glen Shires, Google Inc.

Abstract

This specification defines a JavaScript API to enable web developers to incorporate speech recognition and synthesis into their web pages. It enables developers to use scripting to generate text-to-speech output and to use speech recognition as an input for forms, continuous dictation and control. The JavaScript API allows web pages to control activation and timing and to handle results and alternatives.

It is a fully-functional subset of the specification proposed in the HTML Speech Incubator Group Final Report [1]. Specifically, this subset excludes the underlying transport protocol, the proposed additions to HTML markup, and it defines a simplified subset of the JavaScript API. This subset supports the majority of use-cases and sample code in the Incubator Group Final Report. 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.

Status of This Document

This document is an API proposal from Google Inc. to the Web Applications (WEBAPPS) Working Group.

All feedback is welcome.

No working group is yet responsible for this specification. This is just an informal proposal at this time.

Table of Contents

1 Conformance requirements

All diagrams, examples, and notes in this specification are non-normative, as are all sections explicitly marked non-normative. Everything else in this specification is normative.

The key words "MUST", "MUST NOT", "REQUIRED", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in the normative parts of this document are to be interpreted as described in RFC2119. For readability, these words do not appear in all uppercase letters in this specification. [RFC2119]

Requirements phrased in the imperative as part of algorithms (such as "strip any leading space characters" or "return false and abort these steps") are to be interpreted with the meaning of the key word ("must", "should", "may", etc) used in introducing the algorithm.

Conformance requirements phrased as algorithms or specific steps may be implemented in any manner, so long as the end result is equivalent. (In particular, the algorithms defined in this specification are intended to be easy to follow, and not intended to be performant.)

User agents may impose implementation-specific limits on otherwise unconstrained inputs, e.g. to prevent denial of service attacks, to guard against running out of memory, or to work around platform-specific limitations.

Implementations that use ECMAScript to implement the APIs defined in this specification must implement them in a manner consistent with the ECMAScript Bindings defined in the Web IDL specification, as this specification uses that specification's terminology. [WEBIDL]

2 Introduction

This section is non-normative.

The JavaScript 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. 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. The API is designed to enable both brief (one-shot) speech input and continuous speech input. Speech recognition results are provided to the web page as a list of hypotheses, along with other relevant information for each hypothesis.

This specification is a subset of the API defined in the HTML Speech Incubator Group Final Report. That report is entirely informative since it is not a standards track document. This document is intended to be the basis of a standards track document, and therefore defines portions of that report to be normative. All other portions of that report may be considered informative with regards to this document, and provide an informative background to this document.

3 Use Cases

This section is non-normative.

This specification supports the following use cases, as defined in Section 4 of the Incubator Report.

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

Note that for many usages and implementations, it is possible to avoid the need for Rerecognition by using a larger grammar, or by combining multiple grammars — both of these techniques are supported in this specification.

4 Security and privacy considerations

  1. User agents must only start speech input sessions with explicit, informed user consent. User consent can include, for example:
  2. User agents must give the user an obvious indication when audio is being recorded.
  3. The user agent may also give the user a longer explanation the first time speech input is used, to let the user now what it is and how they can tune their privacy settings to disable speech recording if required.
  4. To minimize the chance of users unwittingly allowing web pages to record speech without their knowledge, implementations must abort an active speech input session if the web page lost input focus to another window or to another tab within the same user agent.

Implementation considerations

This section is non-normative.

  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. Speech input could potentially be used to eavesdrop on users. 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. They could also potentially style the input element to appear as something else and trick the user into clicking them. An example of styling the file input element can be seen at http://www.quirksmode.org/dom/inputfile.html. The above recommendations are intended to reduce this risk of such attacks.

5 API Description

This section is normative.

5.1 The Speech Recognition Interface

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

IDL
          
    [Constructor]
    interface SpeechRecognition : EventTarget {
        // recognition parameters
        attribute SpeechGrammarList grammars;
        attribute DOMString lang;
        attribute boolean continuous;

        // methods to drive the speech interaction
        void start();
        void stop();
        void abort();

        // event methods
        attribute Function onaudiostart;
        attribute Function onsoundstart;
        attribute Function onspeechstart;
        attribute Function onspeechend;
        attribute Function onsoundend;
        attribute Function onaudioend;
        attribute Function onresult;
        attribute Function onnomatch;
        attribute Function onresultdeleted;
        attribute Function onerror;
        attribute Function onstart;
        attribute Function onend;
    };

    interface SpeechRecognitionError {
        const unsigned short OTHER = 0;
        const unsigned short NO_SPEECH = 1;
        const unsigned short ABORTED = 2;
        const unsigned short AUDIO_CAPTURE = 3;
        const unsigned short NETWORK = 4;
        const unsigned short NOT_ALLOWED = 5;
        const unsigned short SERVICE_NOT_ALLOWED = 6;
        const unsigned short BAD_GRAMMAR = 7;
        const unsigned short LANGUAGE_NOT_SUPPORTED = 8;

        readonly attribute unsigned short code;
        readonly attribute DOMString message;
    };

    // Item in N-best list
    interface SpeechRecognitionAlternative {
        readonly attribute DOMString transcript;
        readonly attribute float confidence;
        readonly attribute any interpretation;
    };

    // A complete one-shot simple response
    interface SpeechRecognitionResult {
        readonly attribute unsigned long length;
        getter SpeechRecognitionAlternative item(in unsigned long index);
        readonly attribute boolean final;
    };

    // A collection of responses (used in continuous mode)
    interface SpeechRecognitionResultList {
        readonly attribute unsigned long length;
        getter SpeechRecognitionResult item(in unsigned long index);
    };

    // A full response, which could be interim or final, part of a continuous response or not
    interface SpeechRecognitionEvent : Event {
        readonly attribute SpeechRecognitionResult result;
        readonly attribute SpeechRecognitionError error;
        readonly attribute short resultIndex;
        readonly attribute SpeechRecognitionResultList resultHistory;
    };

    // The object representing a speech grammar
    [Constructor]
    interface SpeechGrammar {
        attribute DOMString src;
        attribute float weight;
    };

    // The object representing a speech grammar collection
    [Constructor]
    interface SpeechGrammarList {
        readonly attribute unsigned long length;
        getter SpeechGrammar item(in unsigned long index);
        void addFromUri(in DOMString src,
                        optional float weight);
        void addFromString(in DOMString string,
                        optional float weight);
    };
          
        

5.1.1 Speech Recognition Attributes

grammars attribute
The grammars attribute stores the collection of SpeechGrammar objects which represent the grammars that are active for this recognition.
lang attribute
This attribute will set the language of the recognition for the request, using a valid BCP 47 language tag. If unset it remains unset for getting in script, but will default to use the lang of the html document root element and associated hierachy. This default value is computed and used when the input request opens a connection to the recognition service.
continuous attribute
When the continuous attribute is set to false the service must only return a single simple recognition response as a result of starting recognition. This represents a request/response single turn pattern of interaction. When the continuous attribute is set to true the service must return a set of recognitions representing more a dictation of multiple recognitions in response to a single starting of recognition. The user agent default value should be false.

5.1.2 Speech Recognition Methods

The start method
When the start method is called it represents the moment in time the web application wishes to begin recognition. When the speech input is streaming live through the input media stream, then this start call represents the moment in time that the service must begin to listen and try to match the grammars associated with this request. If the SpeechRecognition has not yet called open before the start call is made, a call to open is made by the start call (complete with the open event being raised). Once the system is successfully listening to the recognition the user agent must raise a start event.
The stop method
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 received to date. 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. 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. Once the stop method is called the speech service must not collect additional audio and must not continue to listen to the user. The speech service must attempt to return a recognition result (or a nomatch) based on the audio that it has collected to date.
The abort method
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. When the stop method is called the speech service must stop recognizing. The user agent must raise a end event once the speech service is no longer connected.

5.1.3 Speech Recognition Events

The DOM Level 2 Event Model is used for speech recognition events. The methods in the EventTarget interface should be used for registering event listeners. The SpeechRecognition interface also contains convenience attributes for registering a single event handler for each event type.

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. 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).

Unless specified below, the ordering of the different events is undefined. 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.

audiostart event
Fired when the user agent has started to capture audio.
soundstart event
Some sound, possibly speech, has been detected. This must be fired with low latency, e.g. by using a client-side energy detector.
speechstart event
The speech that will be used for speech recognition has started.
speechend event
The speech that will be used for speech recognition has ended. speechstart must always have been fire before speechend.
soundend event
Some sound is no longer detected. This must be fired with low latency, e.g. by using a client-side energy detector. soundstart must always have been fired before soundend.
audioend event
Fired when the user agent has finished capturing audio. audiostart must always have been fired before audioend.
result event
Fired when the speech recognizer returns a result. See here for more information.
nomatch event
Fired when the speech recognizer returns a final result with no recognition hypothesis that meet or exceed the confidence threshold. The result field in the event may contain speech recognition results that are below the confidence threshold or may be null.
resultdeleted event
Fired when the recognizer needs to delete one of the previously returned interim results in a continuous recognition. A simplified example of this might be the recognizer gives an interim result for "hot" as the zeroth index of the continuous result and then gives an interim result of "dog" as the first index. Later the recognize wants to give a final result that is just one word "hotdog". In order to do that it needs to change the zeroth index to "hotdog" and delete the first index. When the first element is deleted the response is the raising of a resultdeleted event. The resultIndex of this event will be the element that was deleted and the resultHistory will have the updated value.
error event
Fired when a speech recognition error occurs. The error attribute must be set to a SpeechRecognitionError object.
start event
Fired when the recognition service has begun to listen to the audio with the intention of recognizing.
end event
Fired when the service has disconnected. The event must always be generated when the session ends no matter the reason for the end.

5.1.4 Speech Recognition Error

The speech recognition error object has two attributes code and message.

code
The code is a numeric error code for whatever has gone wrong. The values are:
OTHER (numeric code 0)
This is the catch all error code.
NO_SPEECH (numeric code 1)
No speech was detected.
ABORTED (numeric code 2)
Speech input was aborted somehow, maybe by some UA-specific behavior such as UI that lets the user cancel speech input.
AUDIO_CAPTURE (numeric code 3)
Audio capture failed.
NETWORK (numeric code 4)
Some network communication that was required to complete the recognition failed.
NOT_ALLOWED (numeric code 5)
The user agent is not allowing any speech input to occur for reasons of security, privacy or user preference.
SERVICE_NOT_ALLOWED (numeric code 6)
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.
BAD_GRAMMAR (numeric code 7)
There was an error in the speech recognition grammar.
LANGUAGE_NOT_SUPPORTED (numeric code 8)
The language was not supported.
message
The message content is implementation specific. This attribute is primarily intended for debugging and developers should not use it directly in their application user interface.

5.1.5 Speech Recognition Alternative

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

transcript
The transcript string represents the raw words that the user spoke.
confidence
The confidence represents a numeric estimate between 0 and 1 of how confident the recognition system is that the recognition is correct. A higher number means the system is more confident.
interpretation
The interpretation represents the semantic meaning from what the user said. This might be determined, for instance, through the SISR specification of semantics in a grammar.

5.1.6 Speech Recognition Result

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.

length
The long attribute represents how many n-best alternatives are represented in the item array.
item
The item getter returns a SpeechRecognitionAlternative from the index into an array of n-best values. If index is greater than or equal to length, this returns null. The user agent must ensure that the length attribute is set to the number of elements in the array. 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).
final
The final boolean must be set to true if this is the final time the speech service will return this particular index value. If the value is false, then this represents an interim result that could still be changed.

5.1.7 Speech Recognition Result List

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

length
The length attribute indicates how many results are represented in the item array.
item
The item getter returns a SpeechRecognitionResult from the index into an array of result values. If index is greater than or equal to length, this returns null. The user agent must ensure that the length attribute is set to the number of elements in the array.

5.1.8 Speech Recognition Event

The Speech Recognition Event is the event that is raised each time there is an interim or final result. The event contains both the current most recent recognized bit (in the result object) as well as a history of the complete recognition session so far (in the results object).

result
The result element is the one single SpeechRecognitionResult that is new as of this request.
resultIndex
The resultIndex must be set to the place in the results array that this particular new result goes. The resultIndex may refer to a previous occupied array index from a previous SpeechRecognitionResultEvent. When this is the case this new result overwrites the earlier result and is a more accurate result; however, when this is the case the previous value must not have been a final result. When continuous was false, the resultIndex must always be 0.
resultHistory
The array of all of the recognition results that have been returned as part of this session. This array must be identical to the array that was present when the last SpeechRecognitionResultEvent was raised, with the exception of the new result value.

5.1.9 Speech Grammar

The SpeechGrammar object represents a container for a grammar. This structure has the following attributes:

src attribute
The required src attribute is the URI for the grammar. Note some services may support builtin grammars that can be specified using a builtin URI scheme.
weight attribute
The optional weight attribute controls the weight that the speech recognition service should use with this grammar. By default, a grammar has a weight of 1. Larger weight values positively weight the grammar while smaller weight values make the grammar weighted less strongly.

5.1.10 Speech Grammar List

The SpeechGrammarList object represents a collection of SpeechGrammar objects. This structure has the following attributes:

length
The length attribute represents how many grammars are currently in the array.
item
The item getter returns a SpeechGrammar from the index into an array of grammars. The user agent must ensure that the length attribute is set to the number of elements in the array. The user agent must ensure that the index order from smallest to largest matches the order in which grammars were added to the array.
The addFromURI method
This method appends a grammar to the grammars array parameter based on URI. The URI for the grammar is specified by the src parameter, which represents the URI for the grammar. Note, some services may support builtin grammars that can be specified by URI. If the weight parameter is present it represents this grammar's weight relative to the other grammar. If the weight parameter is not present, the default value of 1.0 is used.
The addFromString method
This method appends a grammar to the grammars array parameter based on text. The content of the grammar is specified by the string parameter. This content should be encoded into a data: URI when the SpeechGrammar object is created. If the weight parameter is present it represents this grammar's weight relative to the other grammar. If the weight parameter is not present, the default value of 1.0 is used.

5.2 The TTS Interface

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

IDL
          
    [Constructor]
      interface TTS {
          attribute DOMString text;
          attribute DOMString lang;
          readonly attribute boolean paused;
          readonly attribute boolean ended;

          // methods to drive the speech interaction
          void play();
          void pause();
          void stop();

          attribute Function onstart;
          attribute Function onend;
    };
          
        

6 Examples

This section is non-normative.

Examples

Using speech recognition to perform a web search.

Web search by voice with auto-submit
            
  <script type="text/javascript">
    var sr = new SpeechReco();
    sr.onresult = function(event) {
      var q = document.getElementById("q");
      q.value = event.result[0].transcript;
      q.form.submit();
    }
  </script>

  <form action="http://www.example.com/search">
  <input type="search" id="q" name="q">
  <input type="button" value="Speak" onclick="sr.start()">
  </form>
            
          

Using speech synthesis.

TTS
            
  <script type="text/javascript">
     var tts = new TTS();
     function speak(text, lang) {
        tts.text = text;
        tts.lang = lang;
        tts.play();
     }
     speak("Hello world.", "en-US");
  </script>
            
          

This API supports all of the examples in the HTML Speech Incubator Group Final Report that are within the scope of the JavaScript API and are relevant to the Section 3 Use Cases, with minimal or no changes. Specifically, the following are supported from Section 7.1.7.

Acknowledgments

The members of the HTML Speech Incubator Group, and the corresponding Final Report, created the basis for this proposal.

References

[RFC2119]
S. Bradner. Key words for use in RFCs to Indicate Requirement Levels. March 1997. Internet RFC 2119. URL: http://www.ietf.org/rfc/rfc2119.txt
[1]
HTML Speech Incubator Group Final Report, World Wide Web Consortium, 6 December 2011. URL: http://www.w3.org/2005/Incubator/htmlspeech/XGR-htmlspeech/
[WEBIDL]
Web IDL, Cameron McCormack, Editor. World Wide Web Consortium, 19 December 2008. URL: http://dev.w3.org/2006/webapi/WebIDL