使用 @capgo/capacitor-speech-synthesis
用于将文本合成为语音的语音合成插件。
安装
bun add @capgo/capacitor-speech-synthesis
bunx cap sync
bunx cap sync 将插件的原生 code 复制到你的原生项目中。每次升级插件后都要重新运行。
导入
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 个核心方法。监听器与版本辅助函数,以及每个方法的完整规范,均记录在 GitHub 仓库.
监听事件
addListener 会返回一个句柄。调用 handle.remove() 在屏幕卸载时,或者调用 SpeechSynthesis.removeAllListeners() 以清除所有监听器。
完整参考文档
继续使用 @capgo/capacitor-speech-synthesis
如果你正在使用 使用 @capgo/capacitor-speech-synthesis 要规划原生插件工作,请将其与 @capgo/capacitor-speech-synthesis 有关 @capgo/capacitor-speech-synthesis 中的实现细节, 快速入门 有关“入门指南”中的实现细节, Capgo 插件目录 查看 Capgo 插件目录中的产品工作流, Capgo 提供的 Capacitor 插件 有关 Capgo 开发的 Capacitor 插件的实现细节,以及 添加或更新插件 有关添加或更新插件的实现细节。