文本转语音(TTS) API

Spring AI 通过文本转语音模型流式文本转语音模型接口。这让你能够编写跨不同TTS提供商的可移植代码。spring-doc.cadn.net.cn

公共接口

所有TTS提供商都实现了以下共享接口:spring-doc.cadn.net.cn

文本转语音模型

文本转语音模型界面提供了将文本转换为语音的方法:spring-doc.cadn.net.cn

public interface TextToSpeechModel extends Model<TextToSpeechPrompt, TextToSpeechResponse>, StreamingTextToSpeechModel {

    /**
     * Converts text to speech with default options.
     */
    default byte[] call(String text) {
        // Default implementation
    }

    /**
     * Converts text to speech with custom options.
     */
    TextToSpeechResponse call(TextToSpeechPrompt prompt);

    /**
     * Returns the default options for this model.
     */
    default TextToSpeechOptions getDefaultOptions() {
        // Default implementation
    }
}

流式文本转语音模型

流式文本转语音模型接口提供了实时流媒体音频的方法:spring-doc.cadn.net.cn

@FunctionalInterface
public interface StreamingTextToSpeechModel extends StreamingModel<TextToSpeechPrompt, TextToSpeechResponse> {

    /**
     * Streams text-to-speech responses with metadata.
     */
    Flux<TextToSpeechResponse> stream(TextToSpeechPrompt prompt);

    /**
     * Streams audio bytes for the given text.
     */
    default Flux<byte[]> stream(String text) {
        // Default implementation
    }
}

文本转语音提示

文本转语音提示类封装了输入文本和选项:spring-doc.cadn.net.cn

TextToSpeechPrompt prompt = new TextToSpeechPrompt(
    "Hello, this is a text-to-speech example.",
    options
);

文本转语音回复

文本转语音回复类包含生成的音频和元数据:spring-doc.cadn.net.cn

TextToSpeechResponse response = model.call(prompt);
byte[] audioBytes = response.getResult().getOutput();
TextToSpeechResponseMetadata metadata = response.getMetadata();

编写提供者-无关代码

共享TTS接口的一个关键优势是能够编写可与任何TTS提供商无修改的代码。实际的提供商(OpenAI、ElevenLabs 等)由你的 Spring Boot 配置决定,允许你在不更改应用代码的情况下切换提供商。spring-doc.cadn.net.cn

基本服务示例

共享接口允许你编写适用于任何TTS提供商的代码:spring-doc.cadn.net.cn

@Service
public class NarrationService {

    private final TextToSpeechModel textToSpeechModel;

    public NarrationService(TextToSpeechModel textToSpeechModel) {
        this.textToSpeechModel = textToSpeechModel;
    }

    public byte[] narrate(String text) {
        // Works with any TTS provider
        return textToSpeechModel.call(text);
    }

    public byte[] narrateWithOptions(String text, TextToSpeechOptions options) {
        TextToSpeechPrompt prompt = new TextToSpeechPrompt(text, options);
        TextToSpeechResponse response = textToSpeechModel.call(prompt);
        return response.getResult().getOutput();
    }
}

该服务可无缝兼容 OpenAI、ElevenLabs 或其他 TTS 提供商,实际实现由您的 Spring Boot 配置决定。spring-doc.cadn.net.cn

高级示例:多提供者支持

你可以同时构建支持多个TTS提供商的应用程序:spring-doc.cadn.net.cn

@Service
public class MultiProviderNarrationService {

    private final Map<String, TextToSpeechModel> providers;

    public MultiProviderNarrationService(List<TextToSpeechModel> models) {
        // Spring will inject all available TextToSpeechModel beans
        this.providers = models.stream()
            .collect(Collectors.toMap(
                model -> model.getClass().getSimpleName(),
                model -> model
            ));
    }

    public byte[] narrateWithProvider(String text, String providerName) {
        TextToSpeechModel model = providers.get(providerName);
        if (model == null) {
            throw new IllegalArgumentException("Unknown provider: " + providerName);
        }
        return model.call(text);
    }

    public Set<String> getAvailableProviders() {
        return providers.keySet();
    }
}

流媒体音频示例

共享接口还支持实时音频生成的流媒体:spring-doc.cadn.net.cn

@Service
public class StreamingNarrationService {

    private final TextToSpeechModel textToSpeechModel;

    public StreamingNarrationService(TextToSpeechModel textToSpeechModel) {
        this.textToSpeechModel = textToSpeechModel;
    }

    public Flux<byte[]> streamNarration(String text) {
        // TextToSpeechModel extends StreamingTextToSpeechModel
        return textToSpeechModel.stream(text);
    }

    public Flux<TextToSpeechResponse> streamWithMetadata(String text, TextToSpeechOptions options) {
        TextToSpeechPrompt prompt = new TextToSpeechPrompt(text, options);
        return textToSpeechModel.stream(prompt);
    }
}

REST 控制器示例

构建一个与提供者无关的 TTS 的 REST API:spring-doc.cadn.net.cn

@RestController
@RequestMapping("/api/tts")
public class TextToSpeechController {

    private final TextToSpeechModel textToSpeechModel;

    public TextToSpeechController(TextToSpeechModel textToSpeechModel) {
        this.textToSpeechModel = textToSpeechModel;
    }

    @PostMapping(value = "/synthesize", produces = "audio/mpeg")
    public ResponseEntity<byte[]> synthesize(@RequestBody SynthesisRequest request) {
        byte[] audio = textToSpeechModel.call(request.text());
        return ResponseEntity.ok()
            .contentType(MediaType.parseMediaType("audio/mpeg"))
            .header("Content-Disposition", "attachment; filename=\"speech.mp3\"")
            .body(audio);
    }

    @GetMapping(value = "/stream", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    public Flux<byte[]> streamSynthesis(@RequestParam String text) {
        return textToSpeechModel.stream(text);
    }

    record SynthesisRequest(String text) {}
}

基于配置的提供者选择

使用Spring配置文件或属性在提供商间切换:spring-doc.cadn.net.cn

# application-openai.yml
spring:
  ai:
    model:
      audio:
        speech: openai
    openai:
      api-key: ${OPENAI_API_KEY}
      audio:
        speech:
          options:
            model: gpt-4o-mini-tts
            voice: alloy

# application-elevenlabs.yml
spring:
  ai:
    model:
      audio:
        speech: elevenlabs
    elevenlabs:
      api-key: ${ELEVENLABS_API_KEY}
      tts:
        options:
          model-id: eleven_turbo_v2_5
          voice-id: your_voice_id

然后激活所需的提供者:spring-doc.cadn.net.cn

# Use OpenAI
java -jar app.jar --spring.profiles.active=openai

# Use ElevenLabs
java -jar app.jar --spring.profiles.active=elevenlabs

使用便携式选项

为了最大化便携性,只使用公共音文本语音选项接口方法:spring-doc.cadn.net.cn

@Service
public class PortableNarrationService {

    private final TextToSpeechModel textToSpeechModel;

    public PortableNarrationService(TextToSpeechModel textToSpeechModel) {
        this.textToSpeechModel = textToSpeechModel;
    }

    public byte[] createPortableNarration(String text) {
        // Use provider's default options for maximum portability
        TextToSpeechOptions defaultOptions = textToSpeechModel.getDefaultOptions();
        TextToSpeechPrompt prompt = new TextToSpeechPrompt(text, defaultOptions);
        TextToSpeechResponse response = textToSpeechModel.call(prompt);
        return response.getResult().getOutput();
    }
}

使用服务提供者特定功能

当你需要提供者专属功能时,你仍然可以在维护可移植代码库的同时使用它们:spring-doc.cadn.net.cn

@Service
public class FlexibleNarrationService {

    private final TextToSpeechModel textToSpeechModel;

    public FlexibleNarrationService(TextToSpeechModel textToSpeechModel) {
        this.textToSpeechModel = textToSpeechModel;
    }

    public byte[] narrate(String text, TextToSpeechOptions baseOptions) {
        TextToSpeechOptions options = baseOptions;

        // Apply provider-specific optimizations if available
        if (textToSpeechModel instanceof OpenAiAudioSpeechModel) {
            options = OpenAiAudioSpeechOptions.builder()
                .from(baseOptions)
                .model("gpt-4o-tts")  // OpenAI-specific: use high-quality model
                .speed(1.0)
                .build();
        } else if (textToSpeechModel instanceof ElevenLabsTextToSpeechModel) {
            // ElevenLabs-specific options could go here
        }

        TextToSpeechPrompt prompt = new TextToSpeechPrompt(text, options);
        TextToSpeechResponse response = textToSpeechModel.call(prompt);
        return response.getResult().getOutput();
    }
}

便携代码的最佳实践

  1. 依赖接口:始终注入文本转语音模型而非具体实现spring-doc.cadn.net.cn

  2. 使用常见选项:坚持文本语音选项接口方法以实现最大可移植性spring-doc.cadn.net.cn

  3. 优雅处理元数据:不同提供者返回不同的元数据;用通用方式处理spring-doc.cadn.net.cn

  4. 测试多个服务提供商:确保你的代码至少支持两个TTS提供商spring-doc.cadn.net.cn

  5. 记录提供者的假设:如果你依赖特定的提供者行为,务必明确记录spring-doc.cadn.net.cn

服务提供者专属功能

虽然共享接口提供了可移植性,但每个提供者还通过提供者特定的选项类别提供特定功能(例如,OpenAiAudioSpeechOptions,十一实验室语音选项).这些类实现了文本语音选项在增加服务提供者专属功能时,还能提供接口。spring-doc.cadn.net.cn