交談的網頁應用程式 - Speech Synthesis API 簡介

Eric Bidelman

Web Speech API 為 JavaScript 提供語音辨識 (文字轉語音) 和語音合成 (文字轉語音)。由於這個 API 最近才連上 Chrome 33 (行動裝置和電腦),這篇文章會概略介紹後者。如果您有興趣使用語音辨識功能,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);

示範

在 2013 年 Google I/O 大會上,我示範了「更多超棒的網頁版功能:您一直想要的功能」(www.moreawesomeweb.com),示範如何使用 Web Speech API 的 SpeechRecognition 服務,透過 Google Translate API 將麥克風輸入內容自動翻譯成其他語言:

DEMO:http://www.moreawesomeweb.com/demos/speech_translate.html

不過很遺憾,這一步使用未經記錄 (非官方 API) 執行語音合成。我們現在有完整的 Web Speech API 可以朗讀譯文了!我已更新示範以便使用 synthesis API。

瀏覽器支援

Chrome 33 完整支援 Web Speech API,iOS 適用的 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!
}