← 全部文档
插件

语音听写的设置与 JavaScript API

基于 Web Speech API 的语音转文字。工具栏上的麦克风按钮用于开始和停止听写;临时识别结果会实时显示在光标下方。不依赖外部服务——音频由浏览器所使用的语音识别服务商处理。

需要手动启用

这项功能有意设计为需要手动启用——即使在支持的浏览器上,除非启用该插件,否则工具栏按钮是隐藏的。麦克风权限比较敏感;我们不希望麦克风图标默认就出现。

var cfg = {
    dictationEnabled: true,
    dictationLang: "en-US",              // BCP-47
    dictationContinuous: true,
    dictationInterimResults: true,
    dictationAutoPunctuation: true
};
new RichTextEditor("#editor", cfg);

在 ASP.NET Core 标记帮助程序中:

<richtextbox asp-for="Body" toolbar="default"
             enable-dictation="true"
             dictation-lang="en-US"
             dictation-continuous="true"
             dictation-auto-punctuation="true" />

JavaScript API

editor.dictation.start();
editor.dictation.stop();
editor.dictation.toggle();
editor.dictation.isListening();     // boolean
editor.dictation.isSupported();     // false on Firefox

浏览器支持

  • Chrome、Edge、Opera——支持(使用 Google 的云端语音服务)
  • Safari 14.1+(macOS)、iOS 14.5+——支持(视操作系统而定,在设备端或云端处理)
  • Firefox——没有 SpeechRecognition;插件会检测到这一点并隐藏按钮。

第一次点击时会请求麦克风权限。用户可以随时在浏览器的网站设置中撤销该权限。遇到 not-allowed 时,onerror 处理函数会显示一条友好的提示消息。

选项

选项默认值说明
dictationEnabledfalse功能开关。不设置它,插件保持休眠。
dictationLangnavigator.languageBCP-47 语言标记:en-US、es-ES、zh-CN、ja-JP 等。
dictationContinuoustrue为 false 时,识别一句话后即停止。
dictationInterimResultstrue以淡色预览显示浏览器仍在识别中的内容。
dictationAutoPunctuationtrue把每个最终识别片段的首字母大写,如果没有句号则在末尾添加。