createSpeech method

Future<Uint8List> createSpeech({
  1. required String input,
  2. required SpeechModel model,
  3. required SpeechVoice voice,
  4. String? instructions,
  5. SpeechResponseFormat? responseFormat,
  6. num? speed,
  7. String? streamFormat,
})

Generates TTS audio from text (/audio/speech).

final bytes = await client.createSpeech(
  input: 'Hello world',
  model: 'gpt-4o-mini-tts',
  voice: 'nova',
  responseFormat: 'mp3',
);
await File('hello.mp3').writeAsBytes(bytes);

Throws OpenAIRequestException on HTTP ≠ 200.

Implementation

Future<Uint8List> createSpeech({
  /// The text to convert (≤ 4096 chars).
  required String input,

  /// TTS model: `tts-1`, `tts-1-hd`, `gpt-4o-mini-tts`, …
  required SpeechModel model,

  /// Voice name: alloy, ash, ballad, coral, echo, fable, onyx,
  /// nova, sage, shimmer, verse.
  required SpeechVoice voice,

  /// Extra voice instructions (ignored by tts-1 / tts-1-hd).
  String? instructions,

  /// Audio container: mp3 (default), opus, aac, flac, wav, pcm.
  SpeechResponseFormat? responseFormat,

  /// Playback speed 0.25 – 4.0 (default = 1.0).
  num? speed,

  /// Streaming container: audio (default) or sse.
  /// **Note:** `sse` is *not* supported by tts-1 / tts-1-hd.
  String? streamFormat,
}) async {
  final resp = await postJson('/audio/speech', {
    'input': input,
    'model': model.toJson(),
    'voice': voice.toJson(),
    if (instructions != null) 'instructions': instructions,
    if (responseFormat != null) 'response_format': responseFormat.toJson(),
    if (speed != null) 'speed': speed,
    if (streamFormat != null) 'stream_format': streamFormat,
  });

  if (resp.statusCode == 200) {
    // The endpoint returns audio bytes with a Content-Type like audio/mpeg.
    return resp.bodyBytes;
  } else {
    // Let your existing error helper turn the HTTP response
    // into a typed OpenAIRequestException.
    throw OpenAIRequestException.fromHttpResponse(resp);
  }
}