diff --git a/pages/index.js b/pages/index.js index 047bb67..a35e799 100644 --- a/pages/index.js +++ b/pages/index.js @@ -19,6 +19,7 @@ const Home = () => { const [detecting, setDetecting] = useState(false); // 音声認識ステータス const [finalText, setFinalText] = useState(""); // 確定された文章 const [transcript, setTranscript] = useState("ボタンを押して検知開始"); // 認識中の文章 + const [android, setAndroid] = useState(false); // Android chrome用のフラグ // 単語検知 const initialTagValues = ["年収"]; // デフォルト検知単語 const candidates = ["年収", "自由", "成功"]; // 検知単語候補 @@ -35,6 +36,12 @@ const Home = () => { alert("お使いのブラウザには未対応です"); return; } + + // Androidのためのプラグ + if (/Android/i.test(navigator.userAgent)) { + setAndroid(true); + }; + // NOTE: 将来的にwebkit prefixが取れる可能性があるため const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition; @@ -42,12 +49,10 @@ const Home = () => { recognizerRef.current.lang = "ja-JP"; recognizerRef.current.interimResults = true; recognizerRef.current.continuous = true; - recognizerRef.current.onstart = () => { - setDetecting(true); - }; recognizerRef.current.onend = () => { - setTranscript(""); - setDetecting(false); + if (detecting) { + recognizerRef.current.start(); + }; }; recognizerRef.current.onresult = event => { [...event.results].slice(event.resultIndex).forEach(result => { @@ -55,8 +60,13 @@ const Home = () => { if (result.isFinal) { // 音声認識が完了して文章が確定 setFinalText(prevState => { + if (android) { + // Android chromeなら値をそのまま返す + return transcript; + }; return prevState + transcript; }); + // 文章確定したら候補を削除 setTranscript(""); return; } @@ -144,6 +154,7 @@ const Home = () => { color="primary" size="large" onClick={() => { + setDetecting(true); recognizerRef.current.start(); }} > @@ -158,7 +169,8 @@ const Home = () => { color="secondary" size="large" onClick={() => { - recognizerRef.current.onend(); + setDetecting(false); + recognizerRef.current.stop(); }} > {detecting ? "検知停止" : "検知待ち"}