快速开始
这一页给出从空 Expo 工程到产出一份本地 WAV 的最短路径。前提是你已经拿到私有 npm 访问权限;如果还没有,请先看安装与前置条件。
1. 安装两个包
bash
npx expo install @optimalai/react-native@beta
npx @optimalai/model-tools@beta add kokoro-82m-v1.1-zh-int8第二条命令会下载模型包,逐文件校验字节数与 SHA-256,并在你的应用代码旁生成 optimalai-models.ts。详见模型准备。
2. 注册插件与 Metro 资源类型
在 app.json 中:
json
{ "expo": { "plugins": ["@optimalai/react-native"] } }在 metro.config.js 中:
js
const { getDefaultConfig } = require("expo/metro-config");
const { withOptimalAI } = require("@optimalai/react-native/metro");
module.exports = withOptimalAI(getDefaultConfig(__dirname));然后重新构建 Development Build。Expo Go 无法加载本 SDK —— ONNX Runtime 的原生代码必须编译进 App。详见 Expo 与 Metro 配置。
3. 合成
ts
import { createTts } from "@optimalai/react-native";
import { kokoroZhInt8 } from "./optimalai-models";
const tts = createTts({
model: kokoroZhInt8,
voiceId: "zf_001",
numThreads: 4,
});
await tts.load();
const result = await tts.synthesizeToFile({
text: "你好,Hello world.",
voiceId: "af_maple", // 可选:仅覆盖本次合成的音色
});
console.log(result.fileUri);result.fileUri 是一个 file:// URI,指向应用缓存目录里一份 24 kHz、 16-bit、单声道的 WAV。
4. 自己播放
SDK 不负责播放。把 URI 交给你现有的播放器即可:
ts
import { useAudioPlayer } from "expo-audio";
const player = useAudioPlayer(null);
player.replace(result.fileUri);
player.play();5. 用完后释放模型
ts
await tts.reset();整体流程一览
| 步骤 | 调用 | 说明 |
|---|---|---|
| 创建 | createTts({ model, voiceId, numThreads? }) | 开销很小,此时还未接触原生模型。 |
| 加载 | await tts.load() | 冷启动。解析资产 URI 并打开 ONNX session。 |
| 合成 | await tts.synthesizeToFile({ text, voiceId?, outputPath?, speed? }) | 每个 client 同时只能跑一次。 |
| 查询 | tts.status() | unloaded / loading / ready / synthesizing / failed。 |
| 释放 | await tts.reset() | 关闭 session,回到 unloaded。 |