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

浏览器应用中Azure语音转文字JavaScript SDK使用问题咨询

Azure Speech to Text JavaScript SDK 问题解决方案

问题1:识别结果无法插入光标位置,始终追加到文本末尾

解法

通过文本框选区API实时记录光标位置,识别结果返回后手动拆分文本插入到对应位置:

  1. 监听文本框的选区变更事件,实时存储光标索引
  2. 识别回调中根据存储的光标索引拆分原有文本,拼接识别结果后重新赋值给文本框
  3. 插入完成后将光标移动到新插入内容的末尾,方便后续连续输入
    示例代码:
let cursorPosition = 0;
const targetTextarea = document.getElementById('your-textarea-element-id');
// 实时记录光标位置
targetTextarea.addEventListener('selectionchange', () => {
  cursorPosition = targetTextarea.selectionStart;
});

// 识别结果插入处理
function insertResultAtCursor(resultText) {
  const originalText = targetTextarea.value;
  const newText = originalText.slice(0, cursorPosition) + resultText + originalText.slice(cursorPosition);
  targetTextarea.value = newText;
  // 重置光标到插入内容末尾
  cursorPosition += resultText.length;
  targetTextarea.setSelectionRange(cursorPosition, cursorPosition);
}

问题2:清空文本框后重启听写,已删除的旧内容重新出现

解法

该问题是因为复用了旧的识别器实例,实例内部缓存了之前的识别结果。每次重启听写前必须销毁旧实例,重新创建新的识别器,所有结果拼接逻辑由业务层自行控制,不依赖SDK内部的结果累加逻辑:
示例代码:

let speechRecognizer = null;

function startDictation() {
  // 销毁旧识别器实例,清除缓存
  if (speechRecognizer) {
    speechRecognizer.stopContinuousRecognitionAsync(() => {
      speechRecognizer.close();
      speechRecognizer = null;
    });
  }
  // 初始化新的识别器实例
  const speechConfig = SpeechSDK.SpeechConfig.fromSubscription("你的Azure密钥", "你的服务区域");
  const audioConfig = SpeechSDK.AudioConfig.fromDefaultMicrophoneInput();
  speechRecognizer = new SpeechSDK.SpeechRecognizer(speechConfig, audioConfig);

  // 监听单次识别结果,自行处理内容拼接
  speechRecognizer.recognized = (sender, event) => {
    if (event.result.reason === SpeechSDK.ResultReason.RecognizedSpeech) {
      // 直接使用单次识别的增量结果,不调用SDK的累积结果接口
      insertResultAtCursor(event.result.text);
    }
  };

  speechRecognizer.startContinuousRecognitionAsync();
}

问题3:关闭自动标点,支持通过语音指令输入标点

解法

通过SpeechConfig的服务属性配置关闭自动标点,将标点模式设置为显式识别,仅当用户说出对应的标点词汇时才会生成标点符号:

  1. 初始化SpeechConfig时添加punctuation属性配置,值设为explicit
  2. 若有自定义标点映射需求,可在结果回调中添加字符串替换逻辑
    示例代码:
const speechConfig = SpeechSDK.SpeechConfig.fromSubscription("你的Azure密钥", "你的服务区域");
// 关闭自动标点,仅识别显式说出的标点词汇
speechConfig.setServiceProperty("punctuation", "explicit", SpeechSDK.ServicePropertyChannel.UriQueryParameter);

// 可选:自定义标点映射规则
const customPunctMap = {
  "period": ".",
  "question mark": "?",
  "exclamation mark": "!",
  "comma": ",",
  "semicolon": ";"
};

function insertResultAtCursor(resultText) {
  // 替换自定义标点
  Object.entries(customPunctMap).forEach(([keyword, punct]) => {
    const matchReg = new RegExp(`\\s${keyword}\\b`, 'gi');
    resultText = resultText.replace(matchReg, punct);
  });
  // 后续插入逻辑...
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 08:00:02