SpeechSynthesisを使ってテキストを音声に変換

SpeechSynthesisを使ってテキストを音声に変換

window.SpeechSynthesis を使ってテキストを音声に変換。
こんな感じのサンプル作ってみました。

アプリ作成

Vue.jsだけです。Vue.jsで単純アプリを作成します。
App.vueの中身を以下に書き換え。

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

const speech = ref(null)
const text = ref("")
const voice = ref(0)
const voices = ref(null)
const pitch = ref("1")
const rate = ref("1")

onMounted(() => {
  speech.value = window.speechSynthesis;
  // getVoices()が非同期なので以下のイベントで取る必要があるようです。
  speech.value.onvoiceschanged = (event) => {
    voices.value = speech.value.getVoices()
  }
})

// 再生
function play() {
  const utterThis = new SpeechSynthesisUtterance(text.value)
  utterThis.lang = "ja-JP"
  utterThis.voice = voices.value[voice.value]
  utterThis.pitch = pitch.value
  utterThis.rate = rate.value
  speech.value.speak(utterThis)
}
</script>

<template>
  <input v-model="text" size="35"/> <button @click="play">再生</button><br/>
  <div>
    <span>voice</span> 
    <select v-model="voice">
      <option v-for="(item, index) in voices" :value="index">
        {{ item.name }} ({{ item.lang }})
      </option>
    </select>
  </div>
  <div>
    <span>pitch</span> <input type="range" v-model="pitch" min="0" max="2"/>
  </div>
  <div>
    <span>rate</span> <input type="range" v-model="rate" min="0.5" max="2" step="0.1"/>
  </div>
</template>

<style scoped>
span {
  display: inline-block;
  width: 50px;
}
</style>

これだけです。VOICEVOX使うより簡単ですね。
https://github.com/yasuyoshi64/speech-test

SpeechSynthesisについて

SpeechSynthesisの説明は Web Speech API に詳しい説明があります。
SpeechRecognitionと違ってこちらはFireFoxでも動きますね。
最初 getVoices() で空の配列しか返してくれなくて困ってたんですが、ChatGPTに聞いたらgetVoices()は非同期だから以下のようにイベント待たないと値がちゃんと取れないよって回答されました。

  speech.value.onvoiceschanged = (event) => {
    voices.value = speech.value.getVoices()
  }

これで問題なく音声が選択できるようになります。
声も悪くないし、設定も簡単・・・なんですが音声をデータとして取る方法がわからなかった。できないのかな。
VOICEVOXはaudio/wavのデータを返してくれるから再生したりファイルに落としたり応用できるんですが、ここがちょっとな点ですね。

コメント

このブログの人気の投稿

(真)ESP32の開発環境をVSCodeで作る

ESP32にmicroSD接続

ESP32でデバッグ