Skip to content

Commit

Permalink
Merge pull request #7 from yoidea/add-stop-button
Browse files Browse the repository at this point in the history
fix logic for android
  • Loading branch information
rossy0213 committed Jan 5, 2021
2 parents 2f55955 + af17af4 commit 97eafbf
Showing 1 changed file with 18 additions and 8 deletions.
26 changes: 18 additions & 8 deletions pages/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 = ["年収", "自由", "成功"]; // 検知単語候補
Expand All @@ -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;
Expand All @@ -47,24 +54,27 @@ const Home = () => {
};
recognizerRef.current.onend = () => {
setDetecting(false);
if (android && !alertOpen) {
recognizerRef.current.start();
}
};
recognizerRef.current.onresult = event => {
[...event.results].slice(event.resultIndex).forEach(result => {
const transcript = result[0].transcript;
setTranscript(transcript);
if (result.isFinal) {
// 音声認識が完了して文章が確定
setFinalText(prevState => {
return prevState + transcript;
});
setTranscript("");
} else {
// 音声認識の途中経過
if (tagValues.some(value => transcript.includes(value))) {
// NOTE: ユーザーが効果音を追加しなければデフォルトを鳴らす
(userMusic || music).play();
setAlertOpen(true);
}
setTranscript(transcript);
// 音声認識が完了して文章が確定
setFinalText(prevState => {
// Android chromeなら値をそのまま返す
return android ? transcript : (prevState + transcript);
});
// 文章確定したら候補を削除
setTranscript("");
}
});
};
Expand Down

1 comment on commit 97eafbf

@vercel
Copy link

@vercel vercel bot commented on 97eafbf Jan 5, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.