react-native-davoice-tts
Version:
tts library for React Native
64 lines (55 loc) • 1.82 kB
JavaScript
import { NativeModules, NativeEventEmitter, Platform } from 'react-native';
const { DaVoiceTTSBridge } = NativeModules;
if (DaVoiceTTSBridge) {
console.log('DaVoiceTTSBridge is loaded:', DaVoiceTTSBridge);
} else {
console.error('DaVoiceTTSBridge is not linked correctly.');
}
export class DaVoiceTTSInstance {
instanceId; // optional future use
constructor(instanceId = 'default') {
this.instanceId = instanceId;
this._emitter = DaVoiceTTSBridge ? new NativeEventEmitter(DaVoiceTTSBridge) : null;
this._subs = [];
}
async initTTS(modelOrConfig) {
const config =
typeof modelOrConfig === 'string'
? { model: modelOrConfig }
: modelOrConfig || {};
if (!config.model) {
throw new Error("initTTS: missing 'model' (expected string path or { model: string })");
}
return await DaVoiceTTSBridge.initTTS(modelOrConfig);
}
async speak(text, speakerId = 0) {
return await DaVoiceTTSBridge.speak(text, speakerId);
}
async stopSpeaking() {
return await DaVoiceTTSBridge.stopSpeaking();
}
async destroy() {
const res = await DaVoiceTTSBridge.destroy();
// Clean up JS listeners on destroy (good hygiene)
this._subs.forEach(s => {
try { s.remove(); } catch {}
});
this._subs = [];
return res;
}
/**
* Subscribe to “finished speaking the last WAV of the latest synthesize_top call”.
* Returns an unsubscribe function.
*/
onFinishedSpeaking(callback) {
if (!this._emitter) {
throw new Error('NativeEventEmitter not available (bridge missing).');
}
const sub = this._emitter.addListener('onFinishedSpeaking', callback);
this._subs.push(sub);
return () => {
try { sub.remove(); } catch {}
this._subs = this._subs.filter(s => s !== sub);
};
}
}