Last active
August 29, 2015 14:06
-
-
Save Leko/7e7bd71b1d5d45966a7b to your computer and use it in GitHub Desktop.
音声入力と音声出力を一発で行うための関数(Chromeでのみ動作確認)
This file contains hidden or 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
var RECORDER_LANG = 'ja-JP', | |
SPEAKER_LANG = 'ja-JP'; | |
/** | |
* 音声入力を行う関数 | |
* 入力のパース処理は冗長なので内側で処理して、コールバック関数にはパース後の結果を渡す | |
* | |
* @param function onResult 音声解析した結果を受け取って実行する関数 | |
* @param function onError 音声入力中にエラーが有った場合に実行する関数 | |
* @return void | |
*/ | |
function recorder(onResult, onError) { | |
var recorder = new webkitSpeechRecognition(); | |
// 言語を設定 | |
recorder.lang = RECORDER_LANG; | |
// 入力成功時のコールバックを設定 | |
recorder.onresult = function(e) { | |
var result = e.results[0][0].transcript; | |
onResult(result); | |
}; | |
// 入力失敗時のコールバックを設定 | |
recorder.onerror = onError; | |
recorder.start(); | |
} | |
/** | |
* 音声読み上げを行う関数 | |
* 喋り終わったら"何かする"ために喋り終わった後のコールバック関数を指定する | |
* | |
* @param string sentence 喋らせたい言葉 | |
* @param function onEnd 喋り終わったっとにじっこうするコールバック関数 | |
* @return void | |
*/ | |
function speaker(sentence, onEnd) { | |
onEnd = onEnd || function() {}; // NOTE: onEndは省略可能、省略すると何もしない | |
var config = new SpeechSynthesisUtterance(sentence); | |
// 言語を設定 | |
config.lang = SPEAKER_LANG; | |
// 喋り終わった後のコールバックを指定 | |
config.onend = onEnd; | |
// 喋る | |
speechSynthesis.speak(config); | |
} | |
// 使用例(音声入力) | |
recorder( | |
function(result) { | |
console.log('喋った:', result); | |
}, | |
function(e) { | |
console.error('エラー:', e.error); | |
} | |
); | |
// 使用例(音声出力) | |
speaker('こんにちは、私の名前はJohnです', function() { | |
console.log('喋り終わった'); | |
}); | |
speaker('こんにちは、私の名前はJohnです', function() { | |
recorder( | |
function(result) { | |
console.log('喋った:', result); | |
}, | |
function(e) { | |
console.error('エラー:', e.error); | |
} | |
); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment