Happylab Logo
Published on

Day20: Speech Detection

Authors

Introduction: How to use JavaScript and Web Speech API to implement speech recognition functionality.

Project Page: https://iris1114.github.io/javascript30/20_Speech-Detection/

HTML

  • Contains a div container that's contenteditable for displaying speech recognition results.
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Speech Detection</title>
  </head>
  <body>
    <div class="words" contenteditable></div>

    <script src="scripts.js"></script>
  </body>
</html>

JavaScript

  • Uses JavaScript and Web Speech API to implement speech recognition and display results on the page.
// Get SpeechRecognition object
window.SpeechRecognition =
  window.SpeechRecognition || window.webkitSpeechRecognition

const recognition = new SpeechRecognition()
recognition.interimResults = true
recognition.lang = 'en-US'

let p = document.createElement('p')
const words = document.querySelector('.words')
words.appendChild(p)

// Triggered when speech recognition results are available
recognition.addEventListener('result', (e) => {
  const transcript = Array.from(e.results)
    .map((result) => result[0])
    .map((result) => result.transcript)
    .join('')

  // Replace inappropriate words with emoji
  const poopScript = transcript.replace(/poop|poo|shit|dump/gi, '💩')
  p.textContent = poopScript

  // If result is final, create new paragraph
  if (e.results[0].isFinal) {
    p = document.createElement('p')
    words.appendChild(p)
  }
})

// When speech recognition ends, restart it
recognition.addEventListener('end', recognition.start)

// Start speech recognition
recognition.start()

Note

  • Uses window.SpeechRecognition or window.webkitSpeechRecognition to get SpeechRecognition object
  • Sets interimResults to true to get real-time results
  • Uses addEventListener to listen for recognition results and end events
  • Uses regular expressions to replace inappropriate words