会話するウェブアプリ - Speech Synthesis API の概要

Eric Bidelman 氏

Web Speech API は、JavaScript に音声認識(音声文字変換)と音声合成(テキスト読み上げ)を追加します。この投稿では、Chrome 33(モバイルとパソコン)で最近リリースされた API について簡単に説明します。音声認識に興味があるなら、Glen Shires による「Voice Driven Web Apps: Introduction to the Web Speech API」という音声認識機能について、かなりの時点で執筆が行われています。

基本

合成 API の最も基本的な使用方法は、speechSynthesis.speak() と発話を渡すことです。

var msg = new SpeechSynthesisUtterance('Hello World');
window.speechSynthesis.speak(msg);

パラメータを変更して、音量、読み上げ速度、ピッチ、声、言語を調整することもできます。

var msg = new SpeechSynthesisUtterance();
var voices = window.speechSynthesis.getVoices();
msg.voice = voices[10]; // Note: some voices don't support altering params
msg.voiceURI = 'native';
msg.volume = 1; // 0 to 1
msg.rate = 1; // 0.1 to 10
msg.pitch = 2; //0 to 2
msg.text = 'Hello World';
msg.lang = 'en-US';

msg.onend = function(e) {
    console.log('Finished in ' + event.elapsedTime + ' seconds.');
};

speechSynthesis.speak(msg);

音声を設定する

この API を使用して、エンジンがサポートする音声のリストを取得することもできます。

speechSynthesis.getVoices().forEach(function(voice) {
    console.log(voice.name, voice.default ? voice.default :'');
});

次に、発話オブジェクトに .voice を設定して、別の音声を設定します。

var msg = new SpeechSynthesisUtterance('I see dead people!');
msg.voice = speechSynthesis.getVoices().filter(function(voice) { return voice.name == 'Whisper'; })[0];
speechSynthesis.speak(msg);

デモ

Google I/O 2013 の講演で、「More Awesome Web: features you've better web.com」(www.moreawesomeweb.com)では、Web Speech API の SpeechRecognition サービスと Google Translate API を使用してマイクの入力を別の言語に自動翻訳するデモを Google Now や Siri に似たデモで紹介しました。

デモ: http://www.moreawesomeweb.com/demos/speech_translate.html

残念ながら、ドキュメント化されていない(かつ非公式の API)を使用して音声合成を行っていました。これで、完全な Web Speech API を使用して、翻訳を音声で聞くことができるようになりました。合成 API を使用するようにデモを更新しました。

対応ブラウザ

Chrome 33 では Web Speech API が完全にサポートされていますが、iOS7 向けの Safari では部分的にサポートされています。

特徴検出

ブラウザが Web Speech API の各部分を個別にサポートしている場合(Chromium の場合など)は、各機能を個別に検出することをおすすめします。

if ('speechSynthesis' in window) {
    // Synthesis support. Make your web apps talk!
}

if ('SpeechRecognition' in window) {
    // Speech recognition support. Talk to your apps!
}