Components

Speech Recognition

A Stimulus controller that uses the Web Speech API to capture speech and fill an input.


Installation

  1. Install the package

    Terminal
    $ yarn add @stimulus-components/speech-recognition
    
  2. Register the controller in your application

    app/javascript/controllers/index.js
    import { Application } from '@hotwired/stimulus'
    import SpeechRecognition from '@stimulus-components/speech-recognition'
    
    const application = Application.start()
    application.register('speech-recognition', SpeechRecognition)
    

This component uses the Web Speech API. Support and accuracy depend on the browser and may require a secure context (HTTPS).

Example

Speech Recognition

Usage

app/views/index.html
<div data-controller="speech-recognition">
  <textarea data-speech-recognition-target="input" placeholder="Click Start and speak..."></textarea>

  <button
    type="button"
    data-speech-recognition-target="startButton"
    data-action="speech-recognition#start"
    class="hidden"
  >
    Start
  </button>

  <button
    type="button"
    data-speech-recognition-target="stopButton"
    data-action="speech-recognition#stop"
    class="hidden"
  >
    Stop
  </button>

  <span data-speech-recognition-target="indicator" class="hidden">Recording...</span>
</div>

The controller shows it only when the browser supports the Web Speech API. When the API is not supported, the start button, stop button, and indicator stay hidden.

Configuration

AttributeDefaultDescriptionOptional
data-speech-recognition-hidden-classhiddenCSS class toggled to show/hide start, stop, and indicator.

Recognition runs with continuous: true and interimResults: true.

The full transcript (all results joined) is written to the input on each result.

Extending Controller

You can use inheritance to extend the functionality of any Stimulus component:

app/javascript/controllers/speech_recognition_controller.js
import SpeechRecognitionController from "@stimulus-components/speech-recognition"

export default class extends SpeechRecognitionController {
  connect() {
    super.connect()
    console.log("Speech recognition controller connected.")
  }
}

This controller will automatically have access to targets defined in the parent class.

If you override the connect, disconnect or any other methods from the parent, you'll want to call super.method() to make sure the parent functionality is executed.