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

React Native TTS库:如何传递话语标识符至speak()以控制后续操作

在React Native TTS中传递话语标识符并在完成事件中获取的方法

以常用的react-native-tts库为例,你可以通过以下方式实现自定义标识符的传递与回调获取:

核心思路

利用TTS库支持的配置参数传递自定义标识符,或通过映射表关联系统生成的话语ID与自定义ID,在tts-finish事件触发时提取并执行后续操作。

1. 直接传递自定义标识符(部分库支持)

很多RN TTS库允许在speak方法的配置选项中添加自定义字段,这些字段会被携带到完成事件的回调参数中:

import TTS from 'react-native-tts';
import { useEffect } from 'react';

// 监听TTS完成事件
useEffect(() => {
  const finishListener = TTS.addEventListener('tts-finish', (event) => {
    // 从事件参数中提取自定义标识符
    const targetId = event.customId;
    if (targetId) {
      // 执行你的后续逻辑,比如更新状态、触发特定操作
      console.log(`ID为${targetId}的话语朗读完成`);
      handleUtteranceComplete(targetId);
    }
  });

  // 组件卸载时清理监听
  return () => finishListener.remove();
}, []);

// 带标识符的朗读方法
const speakWithCustomId = (text, customId) => {
  TTS.speak(text, {
    customId: customId, // 传递自定义标识符
    rate: 0.8, // 其他配置参数
    volume: 1.0
  });
};

2. 通过映射表关联ID(兼容所有库)

如果你的TTS库不支持自定义字段传递,可以手动维护一个映射表,将系统生成的话语ID与你的自定义ID绑定:

import TTS from 'react-native-tts';
import { useEffect } from 'react';

// 存储系统话语ID与自定义ID的映射
const utteranceIdMap = new Map();

useEffect(() => {
  const finishListener = TTS.addEventListener('tts-finish', (event) => {
    const systemUtteranceId = event.utteranceId;
    // 从映射表中获取自定义ID
    const customId = utteranceIdMap.get(systemUtteranceId);
    if (customId) {
      handleUtteranceComplete(customId);
      utteranceIdMap.delete(systemUtteranceId); // 清理已完成的映射
    }
  });

  return () => finishListener.remove();
}, []);

const speakWithCustomId = (text, customId) => {
  // 生成唯一的系统话语ID
  const systemId = `tts-utterance-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
  utteranceIdMap.set(systemId, customId);
  
  TTS.speak(text, {
    utteranceId: systemId // 将系统ID传入speak配置
  });
};

注意事项

  • 不同TTS库的API细节可能不同,比如有些库的tts-finish事件参数结构、支持的配置字段会有差异,请参考你使用的库的官方文档调整代码。
  • 如果使用映射表,记得在事件回调后删除对应的映射,避免内存泄漏。

内容的提问来源于stack exchange,提问作者Ravindra J. Mandale

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 09:52:33