index.html 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <!DOCTYPE html>
  2. <html lang="zh-CN">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>语音识别示例</title>
  7. </head>
  8. <body>
  9. <h2>语音识别示例</h2>
  10. <p>点击下方按钮开始语音输入:</p>
  11. <!-- 语音输入按钮 -->
  12. <button id="start-btn">开始语音输入</button>
  13. <!-- 显示识别结果 -->
  14. <p>识别结果: <span id="result"></span></p>
  15. <script>
  16. // 检查浏览器是否支持SpeechRecognition
  17. const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
  18. if (!SpeechRecognition) {
  19. alert('你的浏览器不支持语音识别功能,请使用支持的浏览器,例如Google Chrome。');
  20. } else {
  21. const recognition = new SpeechRecognition();
  22. recognition.lang = 'zh-CN'; // 设置识别语言为中文
  23. recognition.interimResults = false; // 不返回临时结果
  24. recognition.maxAlternatives = 1; // 返回的识别结果数量
  25. const startBtn = document.getElementById('start-btn');
  26. const resultSpan = document.getElementById('result');
  27. startBtn.onclick = () => {
  28. recognition.start(); // 开始语音识别
  29. };
  30. recognition.onstart = () => {
  31. console.log('开始语音识别...');
  32. startBtn.disabled = true;
  33. startBtn.textContent = '正在识别...';
  34. };
  35. recognition.onresult = (event) => {
  36. const transcript = event.results[0][0].transcript;
  37. console.log('识别结果:', transcript);
  38. resultSpan.textContent = transcript;
  39. sendToBackend(transcript); // 将识别结果发送到后台
  40. };
  41. recognition.onerror = (event) => {
  42. console.error('识别错误:', event.error);
  43. alert('语音识别出错: ' + event.error);
  44. };
  45. recognition.onend = () => {
  46. console.log('语音识别结束');
  47. startBtn.disabled = false;
  48. startBtn.textContent = '开始语音输入';
  49. };
  50. function sendToBackend(transcript) {
  51. fetch('http://127.0.0.1:5000/msg', {
  52. method: 'POST',
  53. headers: {
  54. 'Content-Type': 'application/json',
  55. 'Access-Control-Allow-Origin':'*'
  56. },
  57. body: JSON.stringify({ msg: transcript }),
  58. // mode: 'no-cors'
  59. })
  60. .then(response => response.json())
  61. .then(data => {
  62. console.log('服务器响应:', data);
  63. })
  64. .catch((error) => {
  65. console.error('发送到后台时发生错误:', error);
  66. });
  67. }
  68. }
  69. </script>
  70. </body>
  71. </html>