Slide 1

Slide 1 text

ブラウザでテキストを読み上げる JavaScript/TypeScript 勉強会 in 神⼾ 2 0 2 4 / 0 4 / 2 7 SAW

Slide 2

Slide 2 text

$(whoami) • ⽒名: 加藤 宗⼀郎 (30歳) • ハンドルネーム: SAW • 関⻄の IT エンジニア コミュニティの賑やかし担当 (⾃称) • ⼤阪在住‧愛知出⾝ • X (旧 Twitter): @azuki_eater • 得意分野: Web アプリケーション開発 • Vue, Laravel 2

Slide 3

Slide 3 text

Web Speech API • Web Speech API は 2種類 • SpeechSynthesis: テキスト読み上げに関する API • SpeechRecognition: ⾳声認識に関する API • 多⾔語に対応 3

Slide 4

Slide 4 text

ブラウザでテキスト読み上げ • テキストの読み上げには SpeechSynthesis インタフェースを利⽤ • 読み上げの開始や停⽌ • ⾳声の種類や⾳量‧ピッチなどの設定 4

Slide 5

Slide 5 text

SpeechSynthesis API の基本的な使い⽅ 1 . SpeechSynthesisUtterance のインスタンスを⽣成 • コンストラクタの引数に読み上げさせる⽂字列を渡す 2 . window.speechSynthesis.speak() で読み上げ • speak() の引数に 1 で⽣成したインスタンスを渡す 5 const utterance = new SpeechSynthesisUtterance('Hello, World.'); window.speechSynthesis.speak(utterance); テキスト読み上げの簡単な実装例

Slide 6

Slide 6 text

⾔語と⾳声の設定 • SpeechSynthesisUtterance の lang プロパティから設定 • SpeechSynthesisUtterance の voice プロパティから設定 • SpeechSynthesisVoice オブジェクトを設定 • window.speechSynthesis.getVoices() で取得できるオブジェクトを設定 6 const utterance = new SpeechSynthesisUtterance('こんにちは'); utterance.lang = 'ja-JP'; // ݴޠΛ೔ຊޠʹઃఆ utterance.voice = window.speechSynthesis .getVoices() // ར༻ՄೳͳԻ੠Λऔಘ .find((x) => x.lang === 'ja-JP'); // ೔ຊޠͷԻ੠ʹߜΓࠐΈ window.speechSynthesis.speak(utterance); テキスト読み上げの⾔語設定

Slide 7

Slide 7 text

⾳量やピッチなどの設定 • SpeechSynthesisUtterance のプロパティから設定 • ⾳量: volume プロパティ • [0, 1] の範囲で設定可能 (0: 最も⼩さい‧ 1: 最も⼤きい) • 初期値は 1 • ピッチ: pitch プロパティ • [0, 2] の範囲で設定可能 (0: 最も低い‧ 2: 最も⾼い) • 初期値は 1 • 速さ: rate プロパティ • [0.1, 10] の範囲で設定可能 (0.1: 最も遅い‧ 10: 最も速い) • 初期値は 1 7

Slide 8

Slide 8 text

読み上げの完了を待つ実装の実現 • speechSynthesis.speak() は読み上げの完了を待たない • 読み上げが完了する前に次の⽂が実⾏される • 読み上げが終わるのを待つには Promise を利⽤ • SpeechSynthesisUtterance のイベントハンドラを登録 • onend のイベントハンドラ内で resolve(); を実⾏ • onerror のイベントハンドラ内で reject(); を実⾏ 8

Slide 9

Slide 9 text

Promise を利⽤して読み上げの完了を待つ実装例 9 const speak = async (text: string) => { return new Promise((resolve, reject) => { const utterance = new SpeechSynthesisUtterance(text); utterance.onend = () => { resolve(); }; utterance.onerror = (e: SpeechSynthesisErrorEvent) => { reject(e); }; window.speechSynthesis.speak(utterance); }); }; SpeechSynthesis API を Promise で wrap console.log('Start speech.'); await speak('Hello, world.'); console.log('End speech.'); wrapper の呼び出し

Slide 10

Slide 10 text

まとめ • ブラウザの⾳声読み上げ機能を紹介 • ⾔語や⾳量‧ピッチなどの調整⽅法を紹介 • 読み上げを待つ⽅法を説明 • Promise を利⽤した実装⽅法を紹介 10

Slide 11

Slide 11 text

ご清聴ありがとうございました