Web Speech API 将语音识别(语音转文字)和语音合成(文字转语音)添加到了 JavaScript 中。该博文简要介绍了后一种 API,因为该 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 大会“More Awesome Web: features you've been needed”(www.moreawesomeweb.com) 中进行了演示,演示了将 Web Speech API 的 SpeechRecognition
服务和 Google Translate API 自动翻译成其他语言:
演示:http://www.moreawesomeweb.com/demos/speech_translate.html
遗憾的是,它使用一个未载明(也非官方)的 API 来执行语音合成。现在,我们拥有完整的 Web Speech API 来说出译文了!我已更新了演示以使用合成 API。
浏览器支持
Chrome 33 全面支持 Web Speech API,而 Safari for iOS7 仅提供部分支持。
功能检测
由于浏览器可能分别支持 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!
}