點燈坊

失くすものさえない今が強くなるチャンスよ

使用 Web Speech API 即時翻譯

Sam Xiao's Avatar 2024-01-14

若想使用語音與即時翻譯,又不想自架後端主機處理,最簡單的方式就是使用 Web Speech API,借用 Google 所提供的後端主機完成。

Version

Vue 3.3

Web Speech API

<template>
  <button @click="onStart">Start</button>
  <button @click="onStop">Stop</button>
  <ul>
    <li v-for="(x, i) in cc" :key="i">
      {{ x }}
    </li>
  </ul>
</template>

<script setup>
import { ref, onMounted } from 'vue'

let cc = ref([])
let speechRecognition = null

onMounted(() => {
  let SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition
  speechRecognition = new SpeechRecognition()
})

let onStart = async () => {
  speechRecognition.continuous = true
  speechRecognition.interimResult = true
  speechRecognition.lang = 'ja-jp'

  speechRecognition.onresult = e => {
    cc.value = Array.from(e.results)
      .map(x => x[0])
      .map(x => x.transcript)
  }

  speechRecognition.start()
}

let onStop = () => {
  cc.value.length = 0
  speechRecognition.stop()
}
</script>

Line 14

let cc = ref([])
let speechRecognition = null
  • cc:儲存要在 template 顯示的翻譯文字
  • speechRecognition:儲存 SpeechRecognition Object

Line 17

onMounted(() => {
  let SpeechRecognition =
    window.SpeechRecognition || window.webkitSpeechRecognition
  speechRecognition = new SpeechRecognition()
})
  • mounted event 建立 SpeechRecognition Object
  • 雖然 Web Speech API 已經是標準,但有的 browser 是以 webkitSpeechRecognition 實現

Line 24

speechRecognition.continuous = true
speechRecognition.interimResult = true
speechRecognition.lang = 'ja-jp'
  • continuous:是否以連續方式翻譯,也就是使用者不斷地講,不斷地翻譯,預設為 false
  • interimResult:是否回傳過渡期間的翻譯結果,預設為 false
  • lang:設定 翻譯語言

Line 28

speechRecognition.onresult = e => {
  cc.value = Array.from(e.results)
    .map(x => x[0])
    .map(x => x.transcript)
}
  • e.resultsArrayLike Object,需使用 Array.from() 轉成普通 Array 後,才能使用 map()

Line 34

speechRecognition.start()
  • start():開始錄音

Line 37

let onStop = () => {
  cc.value.length = 0
  speechRecognition.stop()
}
  • 清空 cc Array
  • stop():停止錄音

Conclusion

  • Web Speech API 讓我們不需準備後端主機,也能簡單地實現語音即時翻譯