使用 @capgo/capacitor-speech-synthesis
Speech Synthesis 插件,用于将文本转换为语音。
安装
bun add @capgo/capacitor-speech-synthesis
bunx cap sync
bunx cap sync 将插件的 native code 复制到你的 native 项目中。每次升级插件后请重新运行。
导入
import { SpeechSynthesis } from '@capgo/capacitor-speech-synthesis';
API 一览
| 方法 | 功能描述 |
|---|---|
speak |
使用指定参数朗读文本。该语音任务将被添加到语音队列中。 |
synthesizeToFile |
将语音合成并保存为音频文件(仅限 Android/iOS)。返回音频文件的保存路径。 |
cancel |
取消所有队列中的语音任务并停止当前朗读。 |
pause |
立即暂停语音朗读。 |
resume |
恢复已暂停的语音朗读。 |
isSpeaking |
检查当前是否正在进行语音合成。 |
isAvailable |
检查设备是否支持语音合成功能。 |
getVoices |
获取所有可用的语音包。 |
getLanguages |
获取所有支持的语言。 |
isLanguageAvailable |
检查是否支持特定语言。 |
isVoiceAvailable |
检查是否支持特定语音包。 |
initialize |
初始化语音合成引擎(针对 iOS 优化)。这可以降低首次语音请求的延迟。 |
activateAudioSession |
使用特定类别激活音频会话(仅限 iOS)。 |
deactivateAudioSession |
停用音频会话(仅限 iOS)。 |
示例
speak()
使用指定选项朗读给定文本。该朗读任务将被添加到语音队列中。
import { SpeechSynthesis } from '@capgo/capacitor-speech-synthesis';
const result = await SpeechSynthesis.speak({
text: 'Hello, world!',
language: 'en-US',
rate: 1.0,
pitch: 1.0,
volume: 1.0,
queueStrategy: 'Add'
});
console.log('Utterance ID:', result.utteranceId);
synthesizeToFile()
将语音合成并保存为音频文件(仅限 Android/iOS)。返回音频保存的文件路径。
import { SpeechSynthesis } from '@capgo/capacitor-speech-synthesis';
const result = await SpeechSynthesis.synthesizeToFile({
text: 'Hello, world!',
language: 'en-US'
});
console.log('Audio file saved at:', result.filePath);
cancel()
取消所有队列中的朗读任务并停止当前语音。
import { SpeechSynthesis } from '@capgo/capacitor-speech-synthesis';
await SpeechSynthesis.cancel();
pause()
立即暂停语音。
import { SpeechSynthesis } from '@capgo/capacitor-speech-synthesis';
await SpeechSynthesis.pause();
resume()
恢复已暂停的语音。
import { SpeechSynthesis } from '@capgo/capacitor-speech-synthesis';
await SpeechSynthesis.resume();
isSpeaking()
检查当前是否正在进行语音合成。
import { SpeechSynthesis } from '@capgo/capacitor-speech-synthesis';
const { isSpeaking } = await SpeechSynthesis.isSpeaking();
console.log('Is speaking:', isSpeaking);
上表列出了 14 个核心方法。有关 Listener 和版本辅助函数以及每个方法的完整规范,请参阅 GitHub 仓库.
监听事件
addListener 返回一个句柄。调用 handle.remove() 当页面卸载时,或 SpeechSynthesis.removeAllListeners() 以清除所有监听器。
完整参考文档
继续阅读:使用 @capgo/capacitor-speech-synthesis
如果你正在使用 使用 @capgo/capacitor-speech-synthesis 来规划 Native Plugin 工作,请将其与 @capgo/capacitor-speech-synthesis 有关 @capgo/capacitor-speech-synthesis 的实现细节, 快速入门 有关“入门指南”中的实现细节, Capgo 插件目录 有关 “Capgo 插件目录” 中的产品工作流, Capgo 开发的 Capacitor 插件 有关 “Capacitor 由 Capgo 开发” 的实现细节,以及 添加或更新插件 有关“添加或更新插件”中的实现细节。