LANG SELRCT

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

Monday, March 11, 2019

入力したテキストをspeechSynthesisで指定した音声でしゃべってもらう


セレクトボックスから音声を選んで
テキストエリアに文章を入力して
playボタンを押すと喋ってくれる

というアプリケーションをGoogle Apps Scriptで作った備忘録






Google Apps Scriptで実現するコードは以下の通りです。




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




index.html
<!DOCTYPE html>
<html>
<body>
  <select id="voiceSelect"></select>
  <br>
  <textarea id="ta" style="width:240px;height:5em;"></textarea>
  <br>
  <button id="bt">play</button>
<script>
speechSynthesis.onvoiceschanged = getVoices;
document.getElementById("bt").onclick = speak;

var voices;

function getVoices() {
  voices = speechSynthesis.getVoices();
  console.log(voices)
  var select = document.getElementById("voiceSelect");
  remove_child("voiceSelect");
  var ta = document.getElementById("ta");
  var values = "";
  for(var i = 0; i < voices.length ; i++) {
    var option = document.createElement('option');
    var lang = voices[i].lang;
    var value = voices[i].name + ' / ' + lang
    option.textContent = value;
    option.setAttribute('data-lang', voices[i].lang);
    option.setAttribute('data-name', voices[i].name);
    option.setAttribute('value', voices[i].name);
    select.appendChild(option);
  }
}

function speak(evt) {
    var msg = new SpeechSynthesisUtterance();
    var value = document.getElementById("ta").value;
    var voice = getSelecteValue();
    var voiceIndex = findVoice(voice);
    msg.volume = 1; // 0 to 1
    msg.rate = 1; // 0.1 to 10
    msg.pitch = 1; //0 to 2
    msg.text = value;
    msg.lang = voices[voiceIndex].lang;
    msg.voice = voices[voiceIndex];
    speechSynthesis.speak(msg);
}

function findVoice(voice) {
  var index;
  for(var i = 0; i < voices.length; i++) {
    if(voices[i].name === voice) {
      index = i;
    }
  }
  return index;
}

function getSelecteValue() {
  var select = document.getElementById("voiceSelect");
  var index = select.selectedIndex;
  var value = select[index].value;
  return value;
}

function remove_child(id) {
  var elem = document.getElementById(id);
  for (var i = elem.childNodes.length - 1; i >= 0; i--) {
    elem.removeChild(elem.childNodes[i]);
  }
}
</script>
</body>
</html>



関連記事


Latest post

スプレッドシートA列にある複数のテキストをスライドに追加したい(Google Apps Script)

今回Google Apps Scriptでやりたいこと GoogleスプレッドシートA列にある複数の値を取得して Googleスライドに渡して 図形オブジェクトのテキストとして追加したい ① スプレッドシートのA列に値を入れておく ② Code.gsのinsertNewShape...