LANG SELRCT

Apps Script Reference  (Create: Create new Spreadsheet | Create new Apps Script

Monday, March 11, 2019

speechSynthesis.getVoices()で配列が返ってこなくて困った。


speechSynthesis.getVoices()で配列が返ってくるらしいので、

  var text = "hello";
  var msg = new SpeechSynthesisUtterance();
  msg.text = text;
  msg.voice = "Alex";
  speechSynthesis.speak(msg);

というコードを書いてみましたがmsg.voice = "Alexがうまくいかずエラーが出る。



いろいろ試してみると、speechSynthesis.onvoiceschanged で解決したので、備忘録として短いコードを書き残しておこう。

(ブラウザによるのかも ちなみに手元のブラウザはChrome)


デモ

以下のボタンをクリックすると Alex の声で hello と言ってくれる。



これをGoogle Apps ScriptのWebアプリで実現するコードを以下に残しました。



コード.gs
function doGet() {
  return HtmlService.createHtmlOutputFromFile("index");
}
意訳
この機能がやること
指定したHTMLファイルを表示する




index.html
<!DOCTYPE html>
<html>
<body>
<button id="bt">Say hello</button>
<script>
speechSynthesis.onvoiceschanged = getVoices;

document.getElementById('bt').onclick = speak;

var voices;

function getVoices() {
  voices = speechSynthesis.getVoices();
}

function speak() {
  var text = "hello";
  var msg = new SpeechSynthesisUtterance();
  msg.text = text;
  msg.voice = voices[1];//Alex
  speechSynthesis.speak(msg);
}

</script>
</body>
</html>


補足:失敗したコード

以下のようにindex.htmlを書くと、こんなエラーが出た
Uncaught TypeError: Failed to set the 'voice' property on 'SpeechSynthesisUtterance': The provided value is not of type 'SpeechSynthesisVoice'.at HTMLTextAreaElement.speak


index.html
<!DOCTYPE html>
<html>
<body>
  <button id="bt">Say hello</button>
<script>
document.getElementById('bt').onclick = speak;

function speak() {
  var text = "hello";
  var msg = new SpeechSynthesisUtterance();
  msg.text = text;
  msg.voice = "Alex";
  speechSynthesis.speak(msg);
}
</script>
</body>
</html>


speechSynthesis.onvoiceschanged = getVoices;
を実行しないとだめらしい。


Latest post

Extracting data from Google Sheets with regular expressions

Introduction Regular expressions are a powerful tool that can be used to extract data from text.  In Google Sheets, regular expressions ca...