synthesize method

Map<String, dynamic> synthesize(
  1. String text, {
  2. String? voiceId,
  3. double speed = 1.0,
  4. double pitch = 0.0,
})

Synthesize speech from text.

Implementation

Map<String, dynamic> synthesize(
  String text, {
  String? voiceId,
  double speed = 1.0,
  double pitch = 0.0,
}) {
  _ensureBackendType('onnx');
  _ensureHandle();

  final textPtr = text.toNativeUtf8();
  final resultPtr = calloc<RacTtsOnnxResultStruct>();

  try {
    final synthesize = _lib.lookupFunction<RacTtsOnnxSynthesizeNative,
        RacTtsOnnxSynthesizeDart>('rac_tts_onnx_synthesize');

    final status = synthesize(
      _handle!,
      textPtr,
      nullptr, // options (could include voice, speed, pitch)
      resultPtr.cast(),
    );

    if (status != RAC_SUCCESS) {
      throw NativeBackendException(
        'TTS synthesis failed: ${RacCore.getErrorMessage(status)}',
        code: status,
      );
    }

    // Extract result from struct
    final result = resultPtr.ref;
    final numSamples = result.numSamples;
    final sampleRate = result.sampleRate;

    // Copy audio samples to Dart
    Float32List samples;
    if (result.audioSamples != nullptr && numSamples > 0) {
      samples = Float32List.fromList(
        result.audioSamples.asTypedList(numSamples),
      );
    } else {
      samples = Float32List(0);
    }

    return {
      'samples': samples,
      'sampleRate': sampleRate,
      'durationMs': result.durationMs,
    };
  } finally {
    calloc.free(textPtr);
    // Free audio samples if allocated by C++
    if (resultPtr.ref.audioSamples != nullptr) {
      RacCore.free(resultPtr.ref.audioSamples.cast());
    }
    calloc.free(resultPtr);
  }
}