JavaScriptで音声合成を扱う際に、「cancel() is not a function」や「Cannot read property 'cancel' of undefined」といったエラーでお困りではありませんか?この記事では、音声合成の停止方法とエラーの解決策について詳しく解説します。

エラーの原因

このエラーが発生する主な原因は以下の2つです:

1. SpeechSynthesisUtteranceインスタンスが正しく生成されていない

2. cancel()メソッドの呼び出しタイミングが適切でない

正しい実装方法

音声合成を適切に停止するには、以下のコードを使用します:

// グローバルなSpeechSynthesisオブジェクトを使用
const synth = window.speechSynthesis;

// 音声停止の関数
function stopSpeaking() {
    if (synth.speaking) {
        synth.cancel();
    }
}

完全な実装例

以下に、音声合成の開始から停止までの完全な実装例を示します:

const synth = window.speechSynthesis;
let utterance = null;

// 音声開始
function startSpeaking(text) {
    utterance = new SpeechSynthesisUtterance(text);
    synth.speak(utterance);
}

// 音声停止
function stopSpeaking() {
    if (synth.speaking) {
        synth.cancel();
    }
}

// 使用例
const button = document.getElementById('speakButton');
button.addEventListener('click', () => {
    startSpeaking('こんにちは、世界!');
});

const stopButton = document.getElementById('stopButton');
stopButton.addEventListener('click', stopSpeaking);

よくあるエラーとその解決策

エラー1: cancel() is not a function

// ❌ 間違った実装
const utterance = new SpeechSynthesisUtterance();
utterance.cancel(); // エラー

// ✅ 正しい実装
const synth = window.speechSynthesis;
synth.cancel();

エラー2: Cannot read property 'cancel' of undefined

// ❌ 間違った実装
speechSynthesis.cancel(); // speechSynthesisが未定義

// ✅ 正しい実装
const synth = window.speechSynthesis;
synth.cancel();

ブラウザ対応状況

音声合成APIは以下の主要ブラウザでサポートされています:

  • Google Chrome 33+
  • Firefox 49+
  • Safari 7+
  • Edge 14+

ただし、ブラウザによって挙動が異なる場合があるため、クロスブラウザテストを推奨します。

まとめ

音声合成の停止処理を実装する際の重要なポイントは:

1. window.speechSynthesisを使用する

2. speaking状態を確認してからcancel()を呼び出す

3. グローバルなsynthオブジェクトを使用する

これらの点に注意して実装することで、安定した音声合成の制御が可能になります。

以上で解説は終わりですが、実際の開発でお困りの際は、ぜひこの記事を参考にしていただければと思います。