Audio Transcription and Text-to-Speech Integration with Spring AI

In Spring AI, Audio Transcription (Speech-to-Text) and Text-to-Speech (TTS) are standardized through dedicated, provider-agnostic model abstractions (TranscriptionModel and TextToSpeechModel). This architecture allows Java applications to ingest spoken audio, convert it into structured text or LLM prompts, and synthesize natural-sounding voice responses without coupling business logic to vendor-specific audio SDKs.

1. Speech-to-Text Architecture (TranscriptionModel)

Spring AI abstracts audio-to-text conversion behind the TranscriptionModel interface, enabling portable transcription pipelines across cloud APIs and local servers.

Core Components & Request Flow

  • Input Resource (AudioTranscriptionPrompt): Wraps a Spring Resource (uploaded MultipartFile, local file, classpath resource, or byte stream) paired with runtime AudioTranscriptionOptions. Importantly, Spring AI passes the resource’s filename extension in the multipart request so the provider knows the audio container format (e.g., .mp3, .wav, .m4a, .flac, .webm).

  • Output Payload (AudioTranscriptionResponse): Contains the transcribed AudioTranscription result alongside AudioTranscriptionResponseMetadata (such as rate-limit headers or provider-specific metrics).

  • Supported Providers:

    • OpenAI & Azure OpenAI: Supports whisper-1 and newer GPT-4o transcription models (gpt-4o-transcribe, gpt-4o-transcribe-diarize).

    • Google GenAI: Supports Gemini-based audio transcription natively.

    • OpenAI-Compatible Local/Cloud Servers: Works seamlessly with local whisper.cpp servers or high-speed cloud endpoints like Groq by overriding the base URL configuration property.

Key Transcription Capabilities & Options

  • Output Formats (response-format): Supports plain text, structured json, verbose_json (including word-level or segment-level timestamps), subtitle formats (srt, vtt), and speaker-labeled diarized_json.

  • Language & Prompt Guidance: Accepting an ISO-639-1 language code improves recognition accuracy and reduces latency, while an optional prompt parameter guides domain spelling, acronyms, or continuity across multi-chunk recordings.

  • Voice Activity Detection (VAD) & Chunking: Supports automatic audio chunking strategies for long recordings.

2. Text-to-Speech Architecture (TextToSpeechModel)

Introduced as a unified abstraction in Spring AI 2.0, TextToSpeechModel (and its reactive counterpart StreamingTextToSpeechModel) standardizes voice synthesis across cloud and local engines.

Core Components & Request Flow

  • Input (TextToSpeechPrompt): Combines the input text string with portable TextToSpeechOptions (model ID, voice selection, playback speed, and audio format).

  • Output (TextToSpeechResponse & Speech): Returns the synthesized audio payload as raw byte[] (for synchronous .call()) or as a reactive Flux<byte[]> stream (for real-time audio playback via .stream()), ready to be served directly from Spring MVC or WebFlux endpoints with MIME types like audio/mpeg or audio/wav.

  • Supported Providers:

    • OpenAI Speech API: Supports tts-1, tts-1-hd, and gpt-4o-mini-tts with selectable voices (alloy, nova, shimmer, etc.) and stylistic voice instructions.

    • ElevenLabs: Integrates ultra-realistic, low-latency expressive voices via spring-ai-elevenlabs.

    • Google GenAI TTS: Connects to Google’s generative text-to-speech capabilities.

    • Local In-JVM Execution (Qxotic jinfer): Runs lightweight TTS models directly inside the JVM without external cloud API calls.

Key Synthesis Options

  • Audio Codecs (response-format): Supports mp3, opus, aac, flac, wav, and raw pcm depending on bandwidth and latency requirements.

  • Playback Speed (speed): Adjustable speaking rate (typically 0.25x to 4.0x).

  • Multi-Provider Switching: Spring Boot auto-configuration properties (spring.ai.model.audio.transcription and spring.ai.model.audio.speech) allow enabling, disabling, or swapping providers across Spring profiles without code changes.

3. Transcription vs. Text-to-Speech Comparison

Dimension Audio Transcription (TranscriptionModel) Text-to-Speech (TextToSpeechModel)
Direction Audio (Resource) $\rightarrow$ Text (String / VTT / SRT / JSON) Text (String) $\rightarrow$ Audio (byte[] / Flux<byte[]>)
Streaming Support Chunked file upload; returns complete transcript per request Native reactive streaming via StreamingTextToSpeechModel (Flux<byte[]>)
Primary Providers OpenAI (Whisper / GPT-4o), Azure OpenAI, Google GenAI, whisper.cpp / Groq OpenAI Speech, ElevenLabs, Google GenAI, Qxotic jinfer (in-JVM)
Key Tuning Controls Language code, style prompt, temperature, timestamp granularity, diarization Voice profile, speaking speed, output codec (mp3, opus, wav, pcm), tone instructions
Typical Enterprise Uses Meeting minutes generation, call-center analytics, voice search, subtitle generation Voice assistants, accessibility screen readers, IVR phone bots, audio summaries

4. End-to-End Voice Assistant & Meeting Pipeline Patterns

Combining TranscriptionModel, ChatClient, and TextToSpeechModel enables complete voice-driven workflows:
  1. Conversational Voice Assistant: User speech is captured in the browser, transcribed via TranscriptionModel, passed into ChatClient (with ChatMemory and RAG advisors), and the LLM’s text reply is streamed back as spoken audio through StreamingTextToSpeechModel.

  2. Automated Meeting Minutes & Action Extractor: Long recordings are split along silence boundaries into size-compliant chunks, transcribed via TranscriptionModel, and fed into ChatClient.call().entity(MeetingMinutes.class) to extract structured decisions, owners, and action items as Java records.

5. Production Best Practices

  • Respect Payload Size & Character Hard Limits: Cloud transcription endpoints typically enforce file size caps (e.g., 25 MB per request on OpenAI Whisper), while TTS APIs enforce input character limits (e.g., 4,096 characters per request). Split long audio along quiet silence boundaries and chunk long text at sentence boundaries before synthesis.

  • Preserve Original File Extensions on Resources: When wrapping uploaded MultipartFile streams or database blobs into a Spring Resource, ensure getFilename() retains a valid audio extension (.mp3, .wav, .m4a), as providers rely on the filename to detect codec headers.

  • Pass Transcripts Safely into Prompts: Never interpolate raw transcribed speech directly into PromptTemplate {placeholder} variables—spoken text containing curly braces or technical syntax can trigger template parsing errors; pass transcripts directly as the UserMessage body instead.

  • Configure Retries Mindfully for Large Audio Uploads: Automatic retries on rate-limit errors (429) re-upload the entire audio payload over the network; configure bounded backoff policies and avoid retrying client format errors (400).

Hands-on Experiment: Voice-Based AI Customer Support System using Spring AI Transcription and Text-to-Speech

Aim: To build a Spring Boot application that listens to a customer’s voice message, answers it with AI, and speaks the answer back using Spring AI audio transcription and text-to-speech.

Description: The application works like a voice helpline for an online store. A customer sends a voice recording with their customer id. The app converts the speech to text, and the AI answers from the store’s FAQs and that customer’s orders. The answer is then converted to an mp3 and returned as a playable audio link. Every call is saved in MySQL with the transcript, the reply text, the customer’s original recording and the spoken reply. There are also separate endpoints for transcription only, speech only, and a text-only version of the assistant for quick testing.

Software / Tools Required

  • JDK 17
  • Spring Boot 3.x
  • Maven
  • MySQL 8.x
  • IDE (IntelliJ IDEA / Eclipse / VS Code)
  • Postman
  • An OpenAI API key (environment variable OPENAI_API_KEY)
  • A speaker or headphones to play the mp3 replies

Steps

  1. Generate the project using Spring Initializr
  2. Add the Spring AI BOM and dependencies in pom.xml
  3. Configure MySQL, the chat model, the transcription model and the speech settings in application.properties
  4. Create the entities VoiceInteraction, AudioFile, FaqEntry and CustomerOrder
  5. Create the repositories
  6. Create TranscriptionService (speech to text)
  7. Create SpeechService (text to speech)
  8. Create SupportDataService and SupportAssistantService (the AI answer)
  9. Create VoiceSupportService that joins all three steps
  10. Create the REST controller
  11. Run the application and test with Postman

Step-by-Step Application Development

Step 1: Generate the Project via Spring Initializr

Field Value
Project Maven
Language Java
Spring Boot 3.4.x (Spring AI 1.0 needs 3.4.x)
Group com.example
Artifact voice-support-system
Packaging Jar
Java 17
Dependencies Spring Web, Spring Data JPA, MySQL Driver, OpenAI (Spring AI)

Step 2: Project Structure

voice-support-system
├── pom.xml
├── README.md
└── src/main
    ├── java/com/example/voicesupport
    │   ├── VoiceSupportApplication.java
    │   ├── entity
    │   │   ├── VoiceInteraction.java
    │   │   ├── AudioFile.java
    │   │   ├── FaqEntry.java
    │   │   └── CustomerOrder.java
    │   ├── repository
    │   │   ├── VoiceInteractionRepository.java
    │   │   ├── AudioFileRepository.java
    │   │   ├── FaqEntryRepository.java
    │   │   └── CustomerOrderRepository.java
    │   ├── service
    │   │   ├── TranscriptionService.java
    │   │   ├── SpeechService.java
    │   │   ├── SupportDataService.java
    │   │   ├── SupportAssistantService.java
    │   │   └── VoiceSupportService.java
    │   └── controller
    │       └── VoiceSupportController.java
    └── resources/application.properties

Step 3: Github Link: 

Step 4: Download the application from above github link, then test the below CURD operations

Running the Application

  1. Start MySQL. The database voice_support_db is created automatically.
  2. Set the key: export OPENAI_API_KEY=sk-... (Windows: setx OPENAI_API_KEY "sk-...", then reopen the terminal).
  3. Run mvn spring-boot:run, or run VoiceSupportApplication from your IDE.
  4. The app starts at http://localhost:8080.

URLs and Request Payloads

Step A: make a test recording with text-to-speech

# Method URL Payload What to check
1 POST /api/audio/speak { "text": "Hello, where is my order ORD5001?" } Returns an mp3. In Postman use Send and Download and save it as question.mp3

Step B: speech-to-text on its own

# Method URL form-data fields What to check
2 POST /api/audio/transcribe file = question.mp3 The transcript matches what was spoken

Step C: the complete voice support call

# Method URL form-data fields What to check
3 POST /api/voice/support file = question.mp3, customerId = CUST101 Transcript, reply text and replyAudioUrl. The reply should mention that ORD5001 is shipped
4 GET /api/voice/{id}/reply-audio none Open in Postman or a browser and listen to the spoken reply
5 GET /api/voice/{id}/question-audio none Plays the customer’s original recording

Use the interactionId from test 3 in place of {id}.

Text-only testing (no audio needed)

# Method URL Payload What to check
6 POST /api/support/text { "customerId": "CUST101", "message": "What is your return policy?" } Answer from the FAQ, in short plain sentences
7 POST /api/support/text { "customerId": "CUST102", "message": "Where is my order ORD5001?" } The assistant must not reveal CUST101’s order, because it only sees CUST102’s orders
8 POST /api/support/text { "customerId": "CUST101", "message": "Can you give me a discount code?" } Says it will connect you to a human agent

History and support data

# Method URL Payload What to check
9 GET /api/voice/interactions?customerId=CUST101 none Saved calls of that customer, newest first
10 GET /api/voice/{id} none One call with transcript and reply
11 GET /api/faqs none The FAQs the assistant uses
12 POST /api/faqs { "topic": "Gift wrapping", "answer": "Gift wrapping is available for 49 rupees per item." } Then ask about gift wrapping with test 6 and see the new FAQ used
13 GET /api/orders/CUST101 none The orders given to the assistant as context

Error cases to try

# Request Expected result
14 /api/audio/transcribe with a .txt file 400, lists the supported audio formats
15 /api/voice/support without customerId 400, customerId is required
16 /api/audio/speak with { "text": "" } 400, text must not be empty

Keep test recordings short, because both transcription and speech are billed by audio length or text length. Audio files must be under 25 MB, and the app limits uploads to 20 MB.

Scroll to Top