Last active
November 29, 2017 13:03
-
-
Save tai-sho/393b873e02778706c29ad339acb57f1b to your computer and use it in GitHub Desktop.
Speech Synthesis APIで文字列を喋らせるクラス
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* HTML5 WebSpeechAPI SpeechSynthesis | |
* @class Speech | |
*/ | |
var Speech = (function() { | |
// 存在チェック | |
if (!'SpeechSynthesisUtterance' in window) { | |
throw new Error('SpeechSynthesisAPI unsupported.'); | |
alert('SpeechSynthesisAPIが対応していないブラウザです。'); | |
return {}; | |
} | |
function Speech(settings) { | |
settings = settings ? settings : {}; | |
this.speaker = new SpeechSynthesisUtterance(); | |
this.speaker.lang = Speech.lang; | |
this.speaker.voice = Speech.voice; | |
this.speaker.volume = ('volume' in settings) ? settings.volume : 1; | |
this.speaker.rate = ('rate' in settings) ? settings.rate : 1.1; | |
this.speaker.pitch = ('pitch' in settings) ? settings.pitch : 1; | |
}; | |
/** | |
* メイン言語 | |
*/ | |
Speech.lang = 'ja-JP'; | |
/** | |
* メイン音声 | |
*/ | |
Speech.voice = null; | |
// 初回だけgetVoiceが取得できない問題の対応 | |
speechSynthesis.onvoiceschanged = function() { | |
var voices = speechSynthesis.getVoices(); | |
for(var i in voices) { | |
if(voices[i]['lang'].replace('_', '-') === Speech.lang) { | |
Speech.voice = voices[i]; | |
} | |
} | |
// 設定された言語が取得できない場合 | |
if(!Speech.voice) { | |
alert('日本語音声が取得できませんでした。'); | |
} | |
}; | |
/** | |
* メッセージの読み上げを行います。 | |
* @param msg | |
*/ | |
Speech.prototype.speak = function(msg) { | |
this.speaker.text = msg; | |
speechSynthesis.speak(this.speaker); | |
}; | |
return Speech; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment