惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

腾讯CDC
The Cloudflare Blog
IT之家
IT之家
V
V2EX
雷峰网
雷峰网
MyScale Blog
MyScale Blog
P
Proofpoint News Feed
Stack Overflow Blog
Stack Overflow Blog
博客园 - Franky
Engineering at Meta
Engineering at Meta
S
SegmentFault 最新的问题
GbyAI
GbyAI
Microsoft Azure Blog
Microsoft Azure Blog
博客园 - 司徒正美
云风的 BLOG
云风的 BLOG
小众软件
小众软件
博客园 - 叶小钗
Blog — PlanetScale
Blog — PlanetScale
C
Check Point Blog
A
About on SuperTechFans
B
Blog
月光博客
月光博客
宝玉的分享
宝玉的分享
Last Week in AI
Last Week in AI

博客园 - wgscd

Git 无法访问 GitHub(unable to access ‘https://github.com/.../.git‘)问题解决教程 RapidOcrNet文字识别OCR C#+Audio绘制麦克风波形 一共免费大模型API AI聊天对话界面的HTML代码。 纯JavaScript代码实现保存Canvas图片到电脑 WPF鼠标拖动改变图片透明度 Fiddler自定义规则保存图片和提示The system proxy was changed自动重连 缩放 div HTML获取摄像头画面,拍照截图保存 JS摄像头手势识别-Handsfree.js HTML,JS 模拟聊天界面UI JS获取元素相对窗口的位置和大小 C# 判断是否安装了ffmpeg shadow-root中的元素定位方法 JS MutationObserver监听DOM元素改变 Webview2动态设置页面video的Blob进行播放 C# 文件分割和文件合并 WPF刮刮乐 JS利用浏览器进行语言识别 WPF设置默认语言地区CultureInfo VS2022推送代码 到github错误: CertGetCertificateChain trust error CERT_TRUST_IS_PARTIAL_CHAIN的解决办法 C#正则表达式匹配候选词 使用ffmpeg去除音频静音
浏览器语音识别-webkitSpeechRecognition
wgscd · 2025-08-11 · via 博客园 - wgscd

浏览器语音识别:webkitSpeechRecognition

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Speech Recognition</title>
    <script>
      window.onload = () => {
        const button = document.getElementById('button');
        button.addEventListener('click', () => {
          if (button.style['animation-name'] === 'flash') {
            recognition.stop();
            button.style['animation-name'] = 'none';
            button.innerText = 'Press to Start';
            content.innerText = '';
          } else {
            button.style['animation-name'] = 'flash';
            button.innerText = 'Press to Stop';
            recognition.start();
          }
        });

        const content = document.getElementById('content');

        const recognition = new webkitSpeechRecognition();
        recognition.continuous = true;
        recognition.interimResults = true;
        recognition.onresult = function (event) {
          let result = '';
          for (let i = event.resultIndex; i < event.results.length; i++) {
            result += event.results[i][0].transcript;
          }
          content.innerText = result;
        };
      };
    </script>
    <style>
      button {
        background: yellow;
        animation-name: none;
        animation-duration: 3s;
        animation-iteration-count: infinite;
      }
      @keyframes flash {
        0% {
          background: red;
        }
        50% {
          background: green;
        }
      }
    </style>
  </head>
  <body>
    <button id="button">Press to Start</button>
    <div id="content"></div>
  </body>
</html>
用1.5秒的间隔来判断它是不是已经完整的。说完了一句话。

例子2:直接输出识别结果:

用1.5秒的间隔来判断它是不是已经完整的。说完了一句话。
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Speech Recognition with Silence Detection</title>
    <script>
        window.onload = () => {
            const button = document.getElementById('button');
            const content = document.getElementById('content');
            const history = document.getElementById('history');
            
            // 配置静默检测参数(毫秒)
            const SILENCE_THRESHOLD = 1500; // 判定为静默的时间
            let silenceTimer = null;
            let isRecognizing = false;
            let finalTranscript = '';
            let currentSentence = '';

            // 初始化语音识别
            const recognition = new (window.SpeechRecognition || window.webkitSpeechRecognition)();
            recognition.continuous = true;
            recognition.interimResults = true;
            recognition.lang = 'zh-CN'; // 可以根据需要更改语言

            // 处理识别结果
            recognition.onresult = function (event) {
                let interimTranscript = '';
                
                // 区分最终结果和临时结果
                for (let i = event.resultIndex; i < event.results.length; i++) {
                    const transcript = event.results[i][0].transcript;
                    if (event.results[i].isFinal) {
                        finalTranscript += transcript;
                    } else {
                        interimTranscript += transcript;
                    }
                }
                
                // 更新当前显示
                currentSentence = finalTranscript + interimTranscript;
                content.innerText = currentSentence;
                
                // 重置静默计时器 - 检测到语音活动
                resetSilenceTimer();
            };

            // 重置静默计时器
            function resetSilenceTimer() {
                clearTimeout(silenceTimer);
                
                if (isRecognizing && currentSentence.trim() !== '') {
                    silenceTimer = setTimeout(() => {
                        // 静默时间达到阈值,认为一句话结束
                        finalizeSentence();
                    }, SILENCE_THRESHOLD);
                }
            }

            // 完成当前句子识别
            function finalizeSentence() {
                if (currentSentence.trim() !== '') {
                    // 添加到历史记录
                    const sentenceElement = document.createElement('div');
                    sentenceElement.className = 'sentence';
                    sentenceElement.textContent = currentSentence;
                    history.prepend(sentenceElement);
                    
                    // 触发自定义事件,供其他功能使用
                    const event = new CustomEvent('sentenceRecognized', {
                        detail: { sentence: currentSentence }
                    });
                    document.dispatchEvent(event);
                    
                    // 清空当前句子
                    finalTranscript = '';
                    currentSentence = '';
                    content.innerText = '';
                }
            }

            // 识别错误处理
            recognition.onerror = function(event) {
                console.error('Recognition error:', event.error);
                if (event.error === 'not-allowed') {
                    alert('请允许麦克风访问以使用语音识别功能');
                }
            };

            // 识别结束处理
            recognition.onend = function() {
                if (isRecognizing) {
                    // 如果仍在识别状态,自动重启识别
                    recognition.start();
                }
            };

            // 按钮点击事件
            button.addEventListener('click', () => {
                if (isRecognizing) {
                    // 停止识别
                    recognition.stop();
                    isRecognizing = false;
                    button.classList.remove('active');
                    button.innerText = 'Press to Start';
                    
                    // 最终确定当前句子
                    if (currentSentence.trim() !== '') {
                        finalizeSentence();
                    }
                } else {
                    // 开始识别
                    recognition.start();
                    isRecognizing = true;
                    button.classList.add('active');
                    button.innerText = 'Press to Stop';
                    finalTranscript = '';
                    currentSentence = '';
                    content.innerText = '';
                }
            });

            // 监听识别完成事件(可用于其他功能)
            document.addEventListener('sentenceRecognized', (event) => {
                console.log('完整句子已识别:', event.detail.sentence);
                // 在这里可以添加对识别结果的后续处理
            });
        };
    </script>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 20px auto;
            padding: 0 20px;
        }

        button {
            background: #4CAF50;
            color: white;
            padding: 12px 24px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            transition: all 0.3s ease;
        }

        button:hover {
            background: #45a049;
        }

        button.active {
            animation: pulse 1.5s infinite;
        }

        @keyframes pulse {
            0% {
                background-color: #4CAF50;
                box-shadow: 0 0 0 0 rgba(76, 175, 80, 0.7);
            }
            70% {
                background-color: #45a049;
                box-shadow: 0 0 0 10px rgba(76, 175, 80, 0);
            }
            100% {
                background-color: #4CAF50;
                box-shadow: 0 0 0 0 rgba(76, 175, 80, 0);
            }
        }

        #content {
            margin: 20px 0;
            padding: 15px;
            min-height: 60px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 18px;
        }

        #history {
            margin-top: 30px;
            padding-top: 20px;
            border-top: 2px solid #eee;
        }

        .sentence {
            padding: 10px;
            margin-bottom: 10px;
            background-color: #f9f9f9;
            border-radius: 4px;
            animation: fadeIn 0.5s ease;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .history-title {
            color: #666;
            font-size: 14px;
            margin-bottom: 10px;
        }
    </style>
</head>
<body>
    <button id="button">Press to Start</button>
    <div id="content" placeholder="识别结果将显示在这里..."></div>
    
    <div id="history">
        <div class="history-title">已识别的句子:</div>
    </div>
</body>
</html>