You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ionic中capacitor-community/speech-recognition插件识别停止检测问题

解决capacitor-community/speech-recognition无法检测停止时机的问题

你当前的代码仅监听了partialResults事件,未处理识别停止的触发逻辑,且仅靠start方法的catch块无法覆盖所有停止场景(比如手动调用stop、系统自动终止识别等)。可以通过以下方式解决:

1. 监听插件的end事件

该插件提供的end事件,无论识别是正常结束、手动停止还是异常终止,都会触发,这是检测停止时机的核心逻辑:

async speechRecognition() {
  if (!this.isPermissionAvailable) {
    await SpeechRecognition.requestPermissions();
    await this.checkPermission();
  }

  if (!this.isMicrophoneDisabled) {
    try {
      await SpeechRecognition.start({
        language: "en-US",
        partialResults: true,
        popup: false,
        maxResults: 0,
      });

      // 监听部分识别结果
      SpeechRecognition.addListener("partialResults", (data: any) => {
        this.annotationValue = data.matches;
        console.log("partialResults was fired", data.matches);
        console.log('present data', data);
        this.chg.detectChanges();
      });

      // 监听识别结束事件
      const endListener = await SpeechRecognition.addListener("end", () => {
        console.log("语音识别已停止");
        // 在这里执行你需要的额外操作
        this.isMicrophoneDisabled = true;
        this.showAnimation = false;
        // 移除当前监听器,避免重复绑定
        endListener.remove();
      });

    } catch (error) {
      console.log("启动识别失败:", error);
      await SpeechRecognition.stop();
      this.isMicrophoneDisabled = true;
      this.showAnimation = false;
    }
  } else {
    // 手动触发停止识别
    await SpeechRecognition.stop();
    this.showAnimation = false;
  }
}

2. 完善手动停止的逻辑

当切换isMicrophoneDisabled状态时,主动调用stop方法确保识别进程终止,此时end事件会被触发,统一处理后续状态更新和额外操作。

3. 清理监听器避免内存泄漏

在组件销毁时,移除所有绑定的监听器:

import { OnDestroy } from '@angular/core';

export class YourComponent implements OnDestroy {
  private listeners: any[] = [];

  async speechRecognition() {
    // ... 原有代码
    const partialListener = await SpeechRecognition.addListener("partialResults", (data: any) => {
      // ... 处理逻辑
    });
    const endListener = await SpeechRecognition.addListener("end", () => {
      // ... 处理逻辑
    });
    this.listeners.push(partialListener, endListener);
  }

  ngOnDestroy() {
    this.listeners.forEach(listener => listener.remove());
  }
}

关键说明

  • end事件覆盖了所有识别停止场景:包括手动调用stop、用户停止说话超时、权限丢失等情况。
  • 不要依赖start方法的catch块处理停止逻辑,它仅能捕获启动阶段的错误,无法覆盖识别过程中的终止情况。

内容的提问来源于stack exchange,提问作者Spunky

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 01:35:11