1
0

More than 1 year has passed since last update.

【UnityWebGL】SpeechSynthesisUtterance(Web Speech API)をiOS Safariで利用できるようにする

Posted at

はじめに

UnityWebGLではブラウザが提供している音声合成API(WebSpeechAPI)のSpeechSynthesisUtteranceを利用することが可能ですが、iOS Safariのみ対応方法が特殊でしたので実装方法を記録します。

iOS Safariでの挙動

speechSynthesis.speakを実行するとエラーの発生等のイベント発行されず、命令が無視される挙動を行います。

iOS SafariのWebSpeechAPI仕様

初回はJavaScript上のユーザーイベントから呼び出す必要があるという制限がありユーザーイベントから呼び出された後は任意に実行することができます。
よって、初回はダミーのユーザーイベントを実行することで本仕様の回避を行います。

実装方法

  • 初回ダミーWebSpeechAPIの実行
    HTML側のJavaScriptに画面をタッチすると音声0のダミー音声合成再生イベントが発生するようにイベントを登録します。
    function handleTouchEnd() {
      // ダミー音声合成を実行
      var speechSynthesis = window.speechSynthesis;
      var utterance = new SpeechSynthesisUtterance('');
      utterance.volume = 0; // 音量を0に設定
      speechSynthesis.speak(utterance);

      // イベントリスナーを削除
      unityCanva.removeEventListener('touchend', handleTouchEnd);
    }

    unityCanvas.addEventListener('touchend', handleTouchEnd);
  • WebSpeechAPIの実行
    二回目以降は他のOSのブラウザと同様に*.jslibファイルからSpeechSynthesisUtteranceを呼び出すことができます。
mergeInto(LibraryManager.library, {
    TextToSpeech: function (speechString) {
        if (!('SpeechSynthesisUtterance' in window)) {
            console.log("SpeechSynthesisUtteranceに非対応のブラウザです。");
        } else {
            var synthesis = new SpeechSynthesisUtterance();
            synthesis.volume = 1;
            synthesis.rate = 1;
            synthesis.pitch = 1;
            synthesis.text = UTF8ToString(speechString);
            synthesis.lang = "ja-JP";
            speechSynthesis.speak(synthesis); // 発言を再生
        }
    },
});

参考スレッド

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0