Skip to content

Generate speech

Use generateSpeech when a provider exposes text-to-speech.

Examples/Sources/GenerateSpeech/main.swift
import Foundation
import SwiftAISDK
@main
struct GenerateSpeechExample {
static func main() async throws {
let provider = try AIProviders.openAI()
let model = try provider.speechModel("gpt-4o-mini-tts")
let result = try await model.generateSpeech(
"Welcome to the SwiftAISDK demo.",
voice: "alloy",
format: "mp3",
speed: 1.0
)
try result.audio.write(to: URL(fileURLWithPath: "welcome.mp3"))
}
}

The protocol method is named speak(_:) for low-level model implementations. Application code should usually prefer the facade spelling generateSpeech.

let result = try await AI.generateSpeech(
"Read this in a calm tone.",
using: model,
instructions: "Calm, precise, and friendly."
)
  • voice selects a provider voice.
  • format requests an output audio format.
  • speed adjusts playback speed when supported.
  • language hints the spoken language.
  • instructions gives delivery or style guidance.
  • providerOptions carries provider-specific controls.
  • extraBody, headers, abortSignal, retryPolicy, and telemetry follow the shared facade behavior.

SpeechResult contains the generated bytes and metadata:

  • audio
  • contentType
  • warnings
  • providerMetadata
  • requestMetadata
  • responseMetadata