JavaScript语言中的语音识别API入门

本文概述

  • 实现
  • 支持的语言
JavaScript API语音识别使Web开发人员可以将语音识别合并到你的网页中。通过此API, 你可以对Chrome 25及更高版本中的语音识别功能进行精细控制和灵活调整。该API是实验性的, 这意味着并非在所有浏览器上都可用。即使在Chrome中, API的某些属性也不被支持。有关更多信息, 请访问我可以使用语音识别。
在本文中, 你将学习如何以最基本的表达方式使用语音识别API。
实现首先, 你需要了解浏览器是否支持API。为此, 你可以使用以下任意代码片段来验证浏览器中的窗口对象是否具有webkitSpeechRecognition属性:
if (!('webkitSpeechRecognition' in window)) {alert("Unable to use the Speech Recognition API"); }// Orif (!window.hasOwnProperty("webkitSpeechRecognition")) {alert("Unable to use the Speech Recognition API"); }// Orif(typeof(webkitSpeechRecognition) != "function"){alert("Unable to use the Speech Recognition API"); }

验证后, 即可开始使用此API。创建webkitSpeechRecognition类的新实例并设置基本属性:
// Create a new instance of SpeechRecognitionvar recognition = new webkitSpeechRecognition(); // Define whether continuous results are returned for each recognition// or only a single result. Defaults to falserecognition.continuous = true; // Controls whether interim results should be returned // Interim results are results that are not yet final // (e.g. the SpeechRecognitionResult.isFinal property is false.)recognition.interimResults = true; // Returns and sets the language of the current SpeechRecognition. // If not specified, this defaults to the HTML lang attribute value// or the user agent's language setting if that isn't set either.// There are a lot of supported languages (go to supported languages at the end of the article)recognition.lang = "en-US";

现在已经设置了基本选项, 你将需要添加一些事件处理程序。在这种情况下, 我们将添加基本侦听器为onerror, onstart, onend和onresult(用于检索识别的文本的事件)。
错误
// Fired when an error happens with the speech recognition// With all the following erro codes:// info-blocked// info-denied// no-speech// aborted// audio-capture// network// not-allowed// service-not-allowed// bad-grammar// language-not-supported// recognition_overlap recognition.onerror = function(event) {console.error(event); };

启动时
// will run when the speech recognition // service has began listening to incoming audio recognition.onstart = function() {console.log('Speech recognition service has started'); };

结束
// run when the speech recognition service has disconnected// (automatically or forced with recognition.stop())recognition.onend = function() {console.log('Speech recognition service disconnected'); };

结果
// This event is triggered when the speech recognition service// returns a result — a word or phrase has been positively //recognized and this has been communicated back to your apprecognition.onresult = function(event) {var interim_transcript = ''; var final_transcript = ''; for (var i = event.resultIndex; i < event.results.length; ++i) {// Verify if the recognized text is the last with the isFinal propertyif (event.results[i].isFinal) {final_transcript += event.results[i][0].transcript; } else {interim_transcript += event.results[i][0].transcript; }}// Choose which result may be useful for youconsole.log("Interim: ", interim_transcript); console.log("Final: ", final_transcript); console.log("Simple: ", event.results[0][0].transcript); };

onresult事件接收自定义偶数对??象作为第一个参数。结果存储在event.results属性中(SpeechRecognitionResultList类型的对象, 该对象存储SpeechRecognitionResult对象, 而该对象又包含SpeechRecognitionAlternative实例, 该实例具有包含文本的transcript属性)。
最后一步, 你需要通过执行识别对象的start方法来启动它, 或者在其运行时执行stop方法来停止它:
// start the speech recognitionrecognition.start(); // Stop the speech recognitionrecognition.stop();

现在, 使用语音识别API的整个功能片段应如下所示:
var recognition = new webkitSpeechRecognition(); recognition.continuous = true; recognition.interimResults = true; recognition.lang = "en-US"; recognition.onerror = function(event) {console.error(event); }; recognition.onstart = function() {console.log('Speech recognition service has started'); }; recognition.onend = function() {console.log('Speech recognition service disconnected'); }; recognition.onresult = function(event) {var interim_transcript = ''; var final_transcript = ''; for (var i = event.resultIndex; i < event.results.length; ++i) {// Verify if the recognized text is the last with the isFinal propertyif (event.results[i].isFinal) {final_transcript += event.results[i][0].transcript; } else {interim_transcript += event.results[i][0].transcript; }}// Choose which result may be useful for youconsole.log("Interim: ", interim_transcript); console.log("Final: ", final_transcript); console.log("Simple: ", event.results[0][0].transcript); }; recognition.start();

一旦执行了start方法, 麦克风权限对话框将显示在浏览器中。
继续并在你的Web或本地服务器中对其进行测试。你可以在此处查看官方Chrome演示中所有可用语言在浏览器中运行的语音识别API的实时演示。
支持的语言目前, 该API在Chrome中支持40种语言。某些语言根据地区有特定的代码(标识符遵循BCP-47格式):
语言 区域 语言代码
南非语 default af-ZA
印尼语 default 编号
马来语 default 毫秒
加泰罗尼亚语 default 胚胎干细胞
切什蒂纳 default cs-CZ
丹斯克 default 大DK
德意志 default 去DE
英语 澳大利亚 en-AU
英语 加拿大 en-CA
英语 印度 en-IN
英语 新西兰 新西兰
英语 南非 en-ZA
英语 英国 en-GB
英语 美国 zh-CN
西班牙文 阿根廷 增强现实
西班牙文 玻利维亚 es-BO
西班牙文 智利 es-CL
西班牙文 哥伦比亚 二氧化碳
西班牙文 哥斯达黎加 胚胎干细胞
西班牙文 厄瓜多尔 es-EC
西班牙文 萨尔瓦多 es-SV
西班牙文 西班牙 ES-ES
西班牙文 Estados Unidos es-US
西班牙文 危地马拉 es-GT
西班牙文 洪都拉斯 血红蛋白
西班牙文 墨西哥 es-MX
西班牙文 尼加拉瓜 es-NI
西班牙文 巴拿马 es-PA
西班牙文 巴拉圭
西班牙文 秘鲁 聚醚砜
西班牙文 波多黎各 es-PR
西班牙文 多米尼加共和国 es-DO
西班牙文 乌拉圭 es-UY
西班牙文 委内瑞拉 VE
Euskara default 欧盟
菲律宾语 default PH
法兰西 default fr-FR
加莱戈 default gl-ES
赫尔瓦茨基 default hr_HR
伊祖祖鲁 default 祖扎
伊斯伦斯卡 default 伊斯兰国
意大利语 意大利 IT
意大利语 Svizzera
列图维奇 default LT
马盖尔 default
荷兰 default NL
挪威语 default
波尔斯基 default 聚乳酸
葡萄牙语 巴西 苯丙氨酸
葡萄牙语 葡萄牙 PT-PT
罗马纳 default 滚装
斯洛文尼亚 default sl-SI
斯洛文尼亚 default sk-SK
omi美 default Fi-FI
斯文斯卡 default sv-SE
丁维特 default 病毒
图尔克 default TR-TR
Ελληνικ? default 遗传资源
български default 血糖
Pусский default RU-RU
Српски default sr-RS
Укра?нська default 英国
??? default ko-KR
中文 普通话(中国大陆) cmn-Hans-CN
中文 普通话(香港) cmn-汉斯-香港
中文 中文(台湾) cmn-Hant-TW
中文 粤语(香港) 粤汉香港
日本语 default ja-JP
?????? default 高输入
??????? default
如果需要Javascript中的上一个表, 则可以使用以下对象, 并且可以如示例中所示对其进行迭代:
var allAvailableLanguages = [{"language": "Afrikaans", "countryCodes": [{"langCode": "af-ZA", "country": "Default"}]}, {"language": "Bahasa Indonesia", "countryCodes": [{"langCode": "id-ID", "country": "Default"}]}, {"language": "Bahasa Melayu", "countryCodes": [{"langCode": "ms-MY", "country": "Default"}]}, {"language": "Català", "countryCodes": [{"langCode": "ca-ES", "country": "Default"}]}, {"language": "?e?tina", "countryCodes": [{"langCode": "cs-CZ", "country": "Default"}]}, {"language": "Dansk", "countryCodes": [{"langCode": "da-DK", "country": "Default"}]}, {"language": "Deutsch", "countryCodes": [{"langCode": "de-DE", "country": "Default"}]}, {"language": "English", "countryCodes": [{"langCode": "en-AU", "country": "Australia"}, {"langCode": "en-CA", "country": "Canada"}, {"langCode": "en-IN", "country": "India"}, {"langCode": "en-NZ", "country": "New Zealand"}, {"langCode": "en-ZA", "country": "South Africa"}, {"langCode": "en-GB", "country": "United Kingdom"}, {"langCode": "en-US", "country": "United States"}]}, {"language": "Espa?ol", "countryCodes": [{"langCode": "es-AR", "country": "Argentina"}, {"langCode": "es-BO", "country": "Bolivia"}, {"langCode": "es-CL", "country": "Chile"}, {"langCode": "es-CO", "country": "Colombia"}, {"langCode": "es-CR", "country": "Costa Rica"}, {"langCode": "es-EC", "country": "Ecuador"}, {"langCode": "es-SV", "country": "El Salvador"}, {"langCode": "es-ES", "country": "Espa?a"}, {"langCode": "es-US", "country": "Estados Unidos"}, {"langCode": "es-GT", "country": "Guatemala"}, {"langCode": "es-HN", "country": "Honduras"}, {"langCode": "es-MX", "country": "México"}, {"langCode": "es-NI", "country": "Nicaragua"}, {"langCode": "es-PA", "country": "Panamá"}, {"langCode": "es-PY", "country": "Paraguay"}, {"langCode": "es-PE", "country": "Perú"}, {"langCode": "es-PR", "country": "Puerto Rico"}, {"langCode": "es-DO", "country": "República Dominicana"}, {"langCode": "es-UY", "country": "Uruguay"}, {"langCode": "es-VE", "country": "Venezuela"}]}, {"language": "Euskara", "countryCodes": [{"langCode": "eu-ES", "country": "Default"}]}, {"language": "Filipino", "countryCodes": [{"langCode": "fil-PH", "country": "Default"}]}, {"language": "Fran?ais", "countryCodes": [{"langCode": "fr-FR", "country": "Default"}]}, {"language": "Galego", "countryCodes": [{"langCode": "gl-ES", "country": "Default"}]}, {"language": "Hrvatski", "countryCodes": [{"langCode": "hr_HR", "country": "Default"}]}, {"language": "IsiZulu", "countryCodes": [{"langCode": "zu-ZA", "country": "Default"}]}, {"language": "íslenska", "countryCodes": [{"langCode": "is-IS", "country": "Default"}]}, {"language": "Italiano", "countryCodes": [{"langCode": "it-IT", "country": "Italia"}, {"langCode": "it-CH", "country": "Svizzera"}]}, {"language": "Lietuvi?", "countryCodes": [{"langCode": "lt-LT", "country": "Default"}]}, {"language": "Magyar", "countryCodes": [{"langCode": "hu-HU", "country": "Default"}]}, {"language": "Nederlands", "countryCodes": [{"langCode": "nl-NL", "country": "Default"}]}, {"language": "Norsk bokm?l", "countryCodes": [{"langCode": "nb-NO", "country": "Default"}]}, {"language": "Polski", "countryCodes": [{"langCode": "pl-PL", "country": "Default"}]}, {"language": "Português", "countryCodes": [{"langCode": "pt-BR", "country": "Brasil"}, {"langCode": "pt-PT", "country": "Portugal"}]}, {"language": "Roman?", "countryCodes": [{"langCode": "ro-RO", "country": "Default"}]}, {"language": "Sloven??ina", "countryCodes": [{"langCode": "sl-SI", "country": "Default"}]}, {"language": "Sloven?ina", "countryCodes": [{"langCode": "sk-SK", "country": "Default"}]}, {"language": "Suomi", "countryCodes": [{"langCode": "fi-FI", "country": "Default"}]}, {"language": "Svenska", "countryCodes": [{"langCode": "sv-SE", "country": "Default"}]}, {"language": "Ti?ng Vi?t", "countryCodes": [{"langCode": "vi-VN", "country": "Default"}]}, {"language": "Türk?e", "countryCodes": [{"langCode": "tr-TR", "country": "Default"}]}, {"language": "Ελληνικ?", "countryCodes": [{"langCode": "el-GR", "country": "Default"}]}, {"language": "български", "countryCodes": [{"langCode": "bg-BG", "country": "Default"}]}, {"language": "Pусский", "countryCodes": [{"langCode": "ru-RU", "country": "Default"}]}, {"language": "Српски", "countryCodes": [{"langCode": "sr-RS", "country": "Default"}]}, {"language": "Укра?нська", "countryCodes": [{"langCode": "uk-UA", "country": "Default"}]}, {"language": "???", "countryCodes": [{"langCode": "ko-KR", "country": "Default"}]}, {"language": "中文", "countryCodes": [{"langCode": "cmn-Hans-CN", "country": "普通话 (中国大陆)"}, {"langCode": "cmn-Hans-HK", "country": "普通话 (香港)"}, {"langCode": "cmn-Hant-TW", "country": "中文 (台灣)"}, {"langCode": "yue-Hant-HK", "country": "粵語 (香港)"}]}, {"language": "日本語", "countryCodes": [{"langCode": "ja-JP", "country": "Default"}]}, {"language": "??????", "countryCodes": [{"langCode": "hi-IN", "country": "Default"}]}, {"language": "???????", "countryCodes": [{"langCode": "th-TH", "country": "Default"}]}]; allAvailableLanguages.forEach(function(item){if(item.countryCodes.length > 1){var allCountries = ""; console.log(item.language + " ("+item.countryCodes.length+" country(s)) "); item.countryCodes.forEach(function(countryItem){console.log(""+countryItem.country + " | "+ countryItem.langCode); }); }else{console.log(item.language + " ["+item.countryCodes[0].langCode+"]"); }});

控制台中谁的输出将是:
// Afrikaans [af-ZA]// Bahasa Indonesia [id-ID]// Bahasa Melayu [ms-MY]// Català [ca-ES]// ?e?tina [cs-CZ]// Dansk [da-DK]// Deutsch [de-DE]// English (7 country(s)) //Australia | en-AU//Canada | en-CA//India | en-IN//New Zealand | en-NZ//South Africa | en-ZA//United Kingdom | en-GB//United States | en-US// Espa?ol (20 country(s)) //Argentina | es-AR//Bolivia | es-BO//Chile | es-CL//Colombia | es-CO//Costa Rica | es-CR//Ecuador | es-EC//El Salvador | es-SV//Espa?a | es-ES//Estados Unidos | es-US//Guatemala | es-GT//Honduras | es-HN//México | es-MX//Nicaragua | es-NI//Panamá | es-PA//Paraguay | es-PY//Perú | es-PE//Puerto Rico | es-PR//República Dominicana | es-DO//Uruguay | es-UY//Venezuela | es-VE// Euskara [eu-ES]// Filipino [fil-PH]// Fran?ais [fr-FR]// Galego [gl-ES]// Hrvatski [hr_HR]// IsiZulu [zu-ZA]// íslenska [is-IS]// Italiano (2 country(s)) //Italia | it-IT//Svizzera | it-CH// Lietuvi? [lt-LT]// Magyar [hu-HU]// Nederlands [nl-NL]// Norsk bokm?l [nb-NO]// Polski [pl-PL]// Português (2 country(s)) //Brasil | pt-BR//Portugal | pt-PT// Roman? [ro-RO]// Sloven??ina [sl-SI]// Sloven?ina [sk-SK]// Suomi [fi-FI]// Svenska [sv-SE]// Ti?ng Vi?t [vi-VN]// Türk?e [tr-TR]// Ελληνικ? [el-GR]// български [bg-BG]// Pусский [ru-RU]// Српски [sr-RS]// Укра?нська [uk-UA]// ??? [ko-KR]// 中文 (4 country(s)) //普通话 (中国大陆) | cmn-Hans-CN//普通话 (香港) | cmn-Hans-HK//中文 (台灣) | cmn-Hant-TW//粵語 (香港) | yue-Hant-HK// 日本語 [ja-JP]// ?????? [hi-IN]// ??????? [th-TH]

【JavaScript语言中的语音识别API入门】编码愉快!

    推荐阅读