使い始める
インストール
npm install @enumura/glyphflow
アプリケーションのエントリーポイントからAPIをimportします。標準の字幕CSSは、このpackage importに含まれます。
import { createKaraokeNarrator, getSpeechSynthesisSupport } from "@enumura/glyphflow";
字幕の描画先を用意する
targetに渡した要素へ字幕用spanを描画します。
<p id="caption" aria-live="polite"></p>
コントロールを有効にする前に対応状況を確認できます。この関数はSSR環境でも安全にimport・呼び出しできます。
const support = getSpeechSynthesisSupport();
if (!support.supported) {
console.log(support.reason);
}
文章を読み上げる
const target = document.querySelector<HTMLElement>("#caption");
if (!target) throw new Error("Caption target is missing");
const narrator = createKaraokeNarrator({
text: "Read each word as its highlight moves across the letters.",
target,
lang: "en-US",
rate: 1.2,
onStateChange(state, detail) {
if (state === "unsupported") console.log(detail?.reason);
},
});
narrator.speak();
speak()を再度呼ぶと現在のセッションをキャンセルして新しいセッションを開始します。UIを破棄するときはdestroy()を呼んでください。
voiceを選ぶ
ブラウザがvoice一覧を非同期で準備することがあります。そのためgetVoices()は準備前には空配列を返します。voiceschangedイベントでUIを更新してください。
import { getVoices } from "@enumura/glyphflow";
function refreshVoices() {
const englishVoices = getVoices().filter((voice) => voice.lang.startsWith("en"));
// englishVoicesでselectなどのUIを更新します。
}
refreshVoices();
speechSynthesis.addEventListener("voiceschanged", refreshVoices);
選択したSpeechSynthesisVoiceをvoiceとして渡します。voiceの設定や保存は利用アプリケーションの責務です。