はじめに
下記でポモドーロタイマーを作ってみたが音を出すことを忘れていたので
Web Audio APIを使ってMP3ファイルを再生しようとしていたところ、
勉強中にWeb Speech APIというAPIを知ったので
Web Speech APIのSpeechSynthesisを使ってタイマーのお知らせ音を設定してみる。
前回の記事
WebAudio API とは(参考記事)
Web Speech API とは(参考記事)
プロジェクトの作成
前回記事にしたソースに引き続き、タイマーのお知らせを実装していく。
Web Speech API の例
// SpeechSynthesisUtteranceオブジェクトを作成
const utterance = new SpeechSynthesisUtterance('Hello');
// 言語を設定 (オプション、日本語の場合は 'ja-JP')
utterance.lang = 'en-US';
// 音量 (0 ~ 1, デフォルト: 1)
utterance.volume = 1;
// ピッチ (0 ~ 2, デフォルト: 1)
utterance.pitch = 1;
// 話す速度 (0.1 ~ 10, デフォルト: 1)
utterance.rate = 1;
// 声を設定 (オプション)
// speechSynthesis.getVoices() で利用可能な声を取得できる
// 例: utterance.voice = voices.find(voice => voice.name === 'Google US English');
// 例: https://developer.mozilla.org/ja/docs/Web/API/SpeechSynthesisUtterance/voice
// 発声
speechSynthesis.speak(utterance);
下記コードでは、
開始時に、TaskあるいはBreakの時間を宣言し、
終了時に、Finishとお知らせしてくれている。
App.jsx
// 略
const longtime = 25 * 60;
const shorttime = 5 * 60;
const [timeIndex, setTimeIndex] = useState(0);
const timecycle = [longtime, shorttime, longtime, shorttime, longtime, shorttime, longtime, longtime]; // (25+5)*3 + (25+25)
const [timeLeft, setTimeLeft] = useState(timecycle[timeIndex]);
const minutes = Math.floor(timeLeft / 60);
const seconds = timeLeft % 60;
const [isActive, setIsActive] = useState(false);
const [isActive, setIsActive] = useState(false);
const explain = timeIndex % 2 == 1 ? `Break ${timecycle[timeIndex] / 60}min.` : `Task ${timecycle[timeIndex] / 60}min.`
// Web Speech APIを設定
const utterance = new SpeechSynthesisUtterance();
utterance.lang = 'en-US';
utterance.volume = 1;
utterance.pitch = 1;
utterance.rate = 1;
useEffect(() => {
let interval = null;
if (isActive && timeLeft > 0) {
interval = setInterval(() => {
setTimeLeft(timeLeft => timeLeft - 1);
}, 1000);
} else if (!isActive && timeLeft !== 0) {
clearInterval(interval);
}
else if (!isActive && timeLeft == 0) {
setTimeLeft(timecycle[timeIndex]);
clearInterval(interval);
}
else if (isActive && timeLeft == 0) {
// Finish時に説明する
utterance.text = explain + ` Finished`;
speechSynthesis.speak(utterance);
}
return () => clearInterval(interval);
}, [isActive, timeLeft, timeIndex]);
const handleStart = () => {
// Start時に説明する
utterance.text = explain;
speechSynthesis.speak(utterance);
setIsActive(true);
};
// 略
完成!
成果物ソース
デモURL
ソース
まとめ
前回作成したタイマーアプリに音出力機能を実装してみた。
普段の業務ではサウンドなどはつけることがないので、
Web Speech APIを学習する良い機会だった。