需要無いと思いますが。
chromeのみ。
SpeechRecognitionAPIの詳細はこちらを。
https://developer.mozilla.org/ja/docs/Web/API/SpeechRecognition
plugin
SpeechRecognition.js
(function( $ ) {
let recognition; // window.SpeechRecognition
// init SpeechRecognition
window.SpeechRecognition = window.SpeechRecognition || webkitSpeechRecognition;
recognition = new webkitSpeechRecognition();
let focus;
let target;
let button;
let click;
$.fn.SpeechRecognizer = function(p) {
focus = ('focus' in p ? p.focus : false);
if (!focus) target = $(this);
if ('click' in p) click = p.click;
recognition.continuous = ('continuous' in p ? p.continuous : true);
recognition.interimResults = ('interimResults' in p ? p.interimResults : true);
recognition.lang = ('lang' in p ? p.lang : 'ja');
recognition.addEventListener('end', ('end' in p ? p.end : end), false);
recognition.addEventListener('audiostart', ('audiostart' in p ? p.audiostart : audiostart), false);
recognition.addEventListener('speechend', ('speechend' in p ? p.speechend : speechend), false);
recognition.addEventListener('result', ('result' in p ? p.result : result), false);
if ('button' in p) {
button = p.button;
$(button).on('click', function(){
$(this).toggleClass("active");
console.log($(this).css('active'));
if ($(this).hasClass('active')) recognition.start();
else recognition.abort();
});
} else recognition.start();
// complate Recognition
var addIndex = 0; // interim result list index
function result(event){
console.log('recognition result ');
var rec = event.results.item(addIndex);
if (!rec) return;
var text = rec.item(0).transcript;
if (focus) target = $(':focus');
target.val(text);
if (rec.isFinal) {
addIndex++;
if (click && text in click) {
$('#'+click[text]).trigger('click');
}
}
}
function audiostart(event){
console.log('recognition audiostart ');
}
// interim
function speechend(event){
console.log('recognition speechend ');
addIndex = 0; // interim reset
}
function end(event){
console.log('recognition end ');
if (!button) recognition.start();
}
};
})( jQuery );
sample
https://minutes-5d614.web.app/test.html
ボタン #start 押下で認識開始、#message に反映。再押下で終了。
$(function() {
$('#message').SpeechRecognizer({
button : $('#start'),
});
});
params
{
focus : boolean[trueの場合フォーカスしているinputに入力(default:false)
continuous : boolean[継続的な返し(default:true)],
interimResults : boolean[interim の結果を返す(default:true)],
lang : string[言語(default:ja)],
end : function[終了イベント],
audiostart : function[認識開始イベント],
speechend : function[認識終了イベント],
result : function[認識結果イベント],
button : string[ボタン。未指定の場合常時待ち受け],
click : object[keyの単語を言ったらvalueのIDがクリックされる]
}
focus とbutton は共存不可
example1
常時待ち受けでフォーカスinputに入力。
$(function() {
$().SpeechRecognizer({
focus : true,
});
});
example2
常時待ち受けで#message に入力。
$(function() {
$('#message').SpeechRecognizer({});
});
example3
常時待ち受けで「あいうえお」と言ったら BtnTest1クリック。
$(function() {
$().SpeechRecognizer({
click : {
'あいうえお' : 'BtnTest1'
}
});
});