• 前端开发攻略---用原生JS在网页中也能实现语音识别


    1、语音识别的过程

    语音识别涉及三个过程:首先,需要设备的麦克风接收这段语音;其次,语音识别服务器会根据一系列语法 (基本上,语法是你希望在具体的应用中能够识别出来的词汇) 来检查这段语音;最后,当一个单词或者短语被成功识别后,结果会以文本字符串的形式返回 (结果可以有多个),以及更多的行为可以设置被触发。

    2、示例 

    2fbe7e5049a14d4b963d0a1005a44938.png

    示例代码:

    您如果想直接尝试的话可以先复制下面代码运气起来试试效果。

    操作方法:将代码运行在浏览器,点击屏幕,允许麦克风权限,然后出说其中一种颜色。

    结果1:识别成功,但是没听清楚您说的什么,页面不会有任何变化。

    结果2:识别成功,页面背景切换为您说的那种颜色。

    结果3:识别失败,失败原因将在页面底部展示。

    1. html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="utf-8" />
    5. <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    6. <meta name="viewport" content="width=device-width" />
    7. <title>title>
    8. <style>
    9. body,
    10. html {
    11. margin: 0;
    12. }
    13. html {
    14. height: 100%;
    15. }
    16. body {
    17. height: inherit;
    18. overflow: hidden;
    19. max-width: 800px;
    20. margin: 0 auto;
    21. }
    22. h1,
    23. p {
    24. font-family: sans-serif;
    25. text-align: center;
    26. padding: 20px;
    27. }
    28. div {
    29. height: 100px;
    30. overflow: auto;
    31. position: absolute;
    32. bottom: 0px;
    33. right: 0;
    34. left: 0;
    35. background-color: rgba(255, 255, 255, 0.2);
    36. }
    37. ul {
    38. margin: 0;
    39. }
    40. .hints span {
    41. text-shadow: 0px 0px 6px rgba(255, 255, 255, 0.7);
    42. }
    43. style>
    44. head>
    45. <body>
    46. <h1>语音识别转换器h1>
    47. <p class="hints">p>
    48. <div>
    49. <p class="output"><em>识别进度展示处em>p>
    50. div>
    51. body>
    52. <script>
    53. var SpeechRecognition = SpeechRecognition || webkitSpeechRecognition
    54. var SpeechGrammarList = SpeechGrammarList || window.webkitSpeechGrammarList
    55. var SpeechRecognitionEvent = SpeechRecognitionEvent || webkitSpeechRecognitionEvent
    56. var colors = [
    57. 'aqua',
    58. 'azure',
    59. 'beige',
    60. 'bisque',
    61. 'black',
    62. 'blue',
    63. 'brown',
    64. 'chocolate',
    65. 'coral',
    66. 'crimson',
    67. 'cyan',
    68. 'fuchsia',
    69. 'ghostwhite',
    70. 'gold',
    71. 'goldenrod',
    72. 'gray',
    73. 'green',
    74. 'indigo',
    75. 'ivory',
    76. 'khaki',
    77. 'lavender',
    78. 'lime',
    79. 'linen',
    80. 'magenta',
    81. 'maroon',
    82. 'moccasin',
    83. 'navy',
    84. 'olive',
    85. 'orange',
    86. 'orchid',
    87. 'peru',
    88. 'pink',
    89. 'plum',
    90. 'purple',
    91. 'red',
    92. 'salmon',
    93. 'sienna',
    94. 'silver',
    95. 'snow',
    96. 'tan',
    97. 'teal',
    98. 'thistle',
    99. 'tomato',
    100. 'turquoise',
    101. 'violet',
    102. 'white',
    103. 'yellow',
    104. ]
    105. var recognition = new SpeechRecognition()
    106. if (SpeechGrammarList) {
    107. var speechRecognitionList = new SpeechGrammarList()
    108. var grammar = '#JSGF V1.0; grammar colors; public = ' + colors.join(' | ') + ' ;'
    109. speechRecognitionList.addFromString(grammar, 1)
    110. recognition.grammars = speechRecognitionList
    111. }
    112. recognition.continuous = false
    113. recognition.lang = 'en-US'
    114. recognition.interimResults = false
    115. recognition.maxAlternatives = 1
    116. var bg = document.querySelector('html')
    117. var hints = document.querySelector('.hints')
    118. var diagnostic = document.querySelector('.output')
    119. var colorHTML = ''
    120. colors.forEach(function (v, i, a) {
    121. colorHTML += '';"> ' + v + ' '
    122. })
    123. hints.innerHTML = '点击页面,然后说出一种颜色来更改页面背景色' + '
      '
      + colorHTML + '.'
    124. let flag = false
    125. document.body.onclick = function () {
    126. if (flag) return
    127. flag = true
    128. recognition.start()
    129. console.log('正识别中...')
    130. diagnostic.textContent = '正识别中...'
    131. }
    132. recognition.onresult = function (event) {
    133. var color = event.results[0][0].transcript
    134. bg.style.backgroundColor = color
    135. flag = false
    136. // console.log('Confidence: ' + event.results[0][0].confidence)
    137. console.log('识别成功,结果是:', color)
    138. diagnostic.textContent = '识别成功,结果是: ' + color + '.'
    139. }
    140. recognition.onspeechend = function () {
    141. recognition.stop()
    142. flag = false
    143. console.log('识别结束')
    144. }
    145. recognition.onnomatch = function (event) {
    146. flag = false
    147. console.log('识别成功,但是没有认出您说的颜色')
    148. diagnostic.textContent = '识别成功,但是没有认出您说的颜色'
    149. }
    150. recognition.onerror = function (event) {
    151. flag = false
    152. let msg = event.error == 'not-allowed' ? '没有麦克风权限' : event.error
    153. console.log('识别错误,原因是:', msg)
    154. diagnostic.textContent = '识别错误,原因是:' + msg
    155. }
    156. script>
    157. html>

    您可能出现的问题:

    一、一直都提示没有麦克风权限

    e9919631827f40399bc4129e1a3e4672.png

    可能原因:

    1、您没有开启当前页面的麦克风功能。

    2、您的电脑或者手机没有麦克风功能。

    解决方法:

    1、您可以重新打开该页面,然后开启当前页面的麦克风权限。

    2、佩戴耳机,利用耳机的麦克风功能

     

    二、页面上只有文字显示,页面效果与示例图不一样

    可能原因:

    1、您使用的浏览器不支持语音识别。

    2、代码有误。

    解决方法:

    1、pc端使用Chrome、Edge、Safari浏览器。手机端使用Safari、Samsung等浏览器或者在微信内部利用WebView打开链接进行访问。

    2、检查代码。

    三、建议使用Edge浏览器,成功率90%以上

    3、代码解析

    判断浏览器支不支持

    1. var SpeechRecognition = SpeechRecognition || webkitSpeechRecognition;
    2. var SpeechGrammarList = SpeechGrammarList || webkitSpeechGrammarList;
    3. var SpeechRecognitionEvent =
    4. SpeechRecognitionEvent || webkitSpeechRecognitionEvent;

    将代码定义希望应用能够识别的语法。语法放在下面定义的变量grammar中:

    1. var colors = [ 'aqua' , 'azure' , 'beige', 'bisque', 'black', 'blue', 'brown', 'chocolate', 'coral' ... ];
    2. var grammar = '#JSGF V1.0; grammar colors; public = ' + colors.join(' | ') + ' ;'

    使用 
    SpeechRecognition() 构造函数,定义一个 speech recognition 实例,控制对于这个应用的识别。还需要使用 SpeechGrammarList() 构造函数,创立一个 speech grammer list 对象

    1. var recognition = new SpeechRecognition();
    2. var speechRecognitionList = new SpeechGrammarList();

    使用 SpeechGrammarList.addFromString() 把语法添加到列表 (list),这个方法接收两个参数,第一个是我们想要添加的包含语法内容的字符串,第二个是对添加的这条语法的权重 (权重值范围是 0~1),权重其实是相对于其他语法,这一条语法的重要程度。添加到列表的语法就是可用的,并且是一个
     SpeechGrammar 实例。

    speechRecognitionList.addFromString(grammar, 1);

    然后通过设置 
    SpeechRecognition.grammars 属性值,把我们的  SpeechGrammarList添加到 speech recognition 实例。在继续往前走之前,我们还需要设置 recognition 实例其他的一些属性:

    • SpeechRecognition.lang :设置识别的是什么语言。
    • SpeechRecognition.interimResults :定义 speech recognition 系统要不要返回临时结果 (interim results),还是只返回最终结果。
    • SpeechRecognition.maxAlternatives :定义每次结果返回的可能匹配值的数量。这有时有用,比如要的结果不明确,你想要用一个列表展示所有可能值,让用户自己从中选择一个正确的。
    1. recognition.grammars = speechRecognitionList;
    2. //recognition.continuous = false;
    3. recognition.lang = "en-US";
    4. recognition.interimResults = false;
    5. recognition.maxAlternatives = 1;

    开始语音识别

    1. document.body.onclick = function () {
    2. if (flag) return
    3. flag = true
    4. recognition.start()
    5. console.log('正识别中...')
    6. diagnostic.textContent = '正识别中...'
    7. }

    接收、处理结果

    一旦语音识别开始,有许多 event handlers 可以用于做结果返回的后续操作,除了识别的结果外还有些零碎的相关信息可供操作,这在收到一个成功的结果时候触发。

    1. recognition.onresult = function (event) {
    2. var color = event.results[0][0].transcript
    3. bg.style.backgroundColor = color
    4. flag = false
    5. // console.log('Confidence: ' + event.results[0][0].confidence)
    6. console.log('识别成功,结果是:', color)
    7. diagnostic.textContent = '识别成功,结果是: ' + color + '.'
    8. }

    停止语音识别服务

    一旦一个单词被识别就不能再说咯 (必须再点击屏幕再次开启语音识别)

    1. recognition.onspeechend = function () {
    2. recognition.stop()
    3. flag = false
    4. console.log('识别结束')
    5. }

    处理未能识别的语音

    你说的内容不在定义的语法中所以识别不了

    1. recognition.onnomatch = function (event) {
    2. flag = false
    3. console.log('识别成功,但是没有认出您说的颜色')
    4. diagnostic.textContent = '识别成功,但是没有认出您说的颜色'
    5. }

    处理 error

    识别出现问题

    1. recognition.onerror = function (event) {
    2. flag = false
    3. let msg = event.error == 'not-allowed' ? '没有麦克风权限' : event.error
    4. console.log('识别错误,原因是:', msg)
    5. diagnostic.textContent = '识别错误,原因是:' + msg
    6. }

     

     

     

     

  • 相关阅读:
    深入了解 npm:Node.js 包管理工具详解
    idea基础配置笔记
    Tomcat基础与优化
    掌握这些插件,分分钟提高你的办公效率90%!
    【Java编程进阶之路--程序流程】
    数组元素替换位置
    QT之QLineEdit简介
    三.listview或tableviw显示
    if ...if...if...else...else...else...的使用
    微信小程序实现文章内容详情
  • 原文地址:https://blog.csdn.net/nibabaoo/article/details/138187630