セレクトボックスから音声を選んで
テキストエリアに文章を入力して
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>
|
関連記事
- 入力したテキストを読み上げてくれるアプリを作る
- 使える音声を取得してみる(speechSynthesis.getVoices())
- speechSynthesis.getVoices()で配列が返ってこなくて困った
参考
SpeechSynthesisUtterance
.lang
https://developer.mozilla.org/ja/docs/Web/API/SpeechSynthesisUtterance/lang
.pitch 0 to 2
.rate 0.1 to 10 話すスピード
.text
.voice 声の名前
https://developer.mozilla.org/ja/docs/Web/API/SpeechSynthesisUtterance/voice
.volume 0 to 1
SpeechSynthesisUtterance
.lang
https://developer.mozilla.org/ja/docs/Web/API/SpeechSynthesisUtterance/lang
.pitch 0 to 2
.rate 0.1 to 10 話すスピード
.text
.voice 声の名前
https://developer.mozilla.org/ja/docs/Web/API/SpeechSynthesisUtterance/voice
.volume 0 to 1
SpeechSynthesis.getVoices()