Use the Java SDK to call the CosyVoice speech synthesis API in non-streaming or streaming mode.
Prerequisites
- An Obtain an API key, configured as an environment variable
- The DashScope Java SDK, version 2.22.15 or later. Install the latest version.
HttpSpeechSynthesizer class
Package: com.alibaba.dashscope.audio.http_tts.HttpSpeechSynthesizer
Description: HTTP-based speech synthesis that supports non-streaming and streaming modes.
Constructor
DASHSCOPE_API_KEY environment variable. If that variable is not set, it falls back to Constants.apiKey.
callAndReturnAudio() — non-streaming (returns audio data)
Method signature:
| Parameter | Type | Description |
|---|---|---|
param | HttpSpeechSynthesisParam | The speech synthesis parameter object that contains model, text, voice, and other configurations. |
ByteBuffer containing the complete audio data. Call remaining() to get the audio size in bytes.
call() — non-streaming (returns audio URL)
Method signature:
| Parameter | Type | Description |
|---|---|---|
param | HttpSpeechSynthesisParam | The speech synthesis parameter object. |
HttpSpeechSynthesisResult object. Call getAudioInfo().getUrl() to get the audio download URL. The URL expires after a fixed period. Call getAudioInfo().getExpiresAt() to get the expiration time.
streamCall() — streaming
Method signature:
| Parameter | Type | Description |
|---|---|---|
param | HttpSpeechSynthesisParam | The speech synthesis parameter object. |
callback | ResultCallback<HttpSpeechSynthesisResult> | The callback object. Implement onEvent (receives audio chunks), onComplete (synthesis finished), and onError (error handling). |
com.alibaba.dashscope.common.ResultCallback is a generic callback interface provided by the DashScope SDK. Implement the following three methods:
| Method | Parameter | Description |
|---|---|---|
onEvent | HttpSpeechSynthesisResult result | Triggered on each audio chunk. Call result.hasAudioData() to check for audio data and result.getAudioDataSize() to get the chunk size. |
onComplete | None | Triggered when synthesis completes and all audio chunks have been received. |
onError | Exception e | Triggered on synthesis error. Call e.getMessage() to get the error details. |
HttpSpeechSynthesisParam class
Package: com.alibaba.dashscope.audio.http_tts.HttpSpeechSynthesisParam
Use the Builder pattern to construct parameter objects.
Some parameters don't have dedicated Builder methods. Set them using the parameter(String key, Object value) method or the parameters(Map<String, Object>) method inherited from the parent class.
| Method | Type | Required | Description |
|---|---|---|---|
| model(String) | String | Yes | The speech synthesis model.Valid values:
|
| text(String) | String | Yes | The text to synthesize.SSML and LaTeX format inputs are supported. Replace the text content with the corresponding format.
|
| voice(String) | String | Yes | The voice for synthesis.Valid values:
|
| format(String) | String | No | The audio format.Default value: mp3.Valid values:
|
| sampleRate(int) | int | No | The audio sample rate in Hz.Valid values: 8000, 16000, 22050 (default), 24000, 44100, 48000. |
| volume(int) | int | No | The volume level.Default value: 50.Valid values: [0, 100]. |
| rate(float) | float | No | The speech rate.Default value: 1.0.Valid values: [0.5, 2.0]. |
| pitch(float) | float | No | The pitch.Default value: 1.0.Valid values: [0.5, 2.0]. |
enable_ssml | boolean | No | Enables SSML. When set to true, pass SSML-formatted text in the text parameter. For supported SSML tags and usage, see SSML. For the SSML usage restrictions (supported models, voices, and APIs), see Limitations.Default: false.Set enable_ssml using the HttpSpeechSynthesisParam instance's parameter method or parameters method: |
word_timestamp_enabled | boolean | No | Specifies whether to enable word-level timestamps.Default value: false.Available only in streaming output mode. Supported voices: cloned voices of cosyvoice-v3.5-plus, cosyvoice-v3.5-flash, cosyvoice-v3-flash, cosyvoice-v3-plus, cosyvoice-v2, and system voices marked as supported in CosyVoice Voice list. Cloned voices of other models do not support this feature.Set word_timestamp_enabled using the HttpSpeechSynthesisParam instance's parameter method or parameters method: |
seed | int | No | The random seed for synthesis. Different seeds produce different outputs. With identical model version, text, voice, and other parameters, the same seed reproduces the same output.Default value: 0.Valid values: [0, 65535].Set seed using the HttpSpeechSynthesisParam instance's parameter method or parameters method: |
language_hints | List | No | Specifies the target language for speech synthesis to improve output quality.Use this parameter when numbers, abbreviations, or symbols are not pronounced as expected, or when synthesis quality for secondary languages is poor. Examples:
Valid values
language_hints using the HttpSpeechSynthesisParam instance's parameter method or parameters method: |
instruction | String | No | An instruction that controls the synthesis behavior, such as dialect, emotion, or role.For usage details, see Non-real-time speech synthesis.Set instruction using the HttpSpeechSynthesisParam instance's parameter method or parameters method: |
bit_rate | int | No | The audio bitrate in kbps.Default value: 32.Valid values: [6, 510].Set bit_rate using the HttpSpeechSynthesisParam instance's parameter method or parameters method: |
enable_aigc_tag | boolean | No | Specifies whether to embed an AIGC watermark in the generated audio. When set to true, the watermark is embedded in audio files of supported formats (wav/mp3/opus).Default value: false. Only cosyvoice-v3-flash, cosyvoice-v3-plus, cosyvoice-v2 support this feature. enable_aigc_tag using the HttpSpeechSynthesisParam instance's parameter method or parameters method: |
aigc_propagator | String | No | Sets the ContentPropagator field in the AIGC watermark, identifying the content propagator. Takes effect only when enable_aigc_tag is true.Default value: Alibaba Cloud UID.Only cosyvoice-v3-flash, cosyvoice-v3-plus, cosyvoice-v2 support this feature. aigc_propagator using the HttpSpeechSynthesisParam instance's parameter method or parameters method: |
aigc_propagate_id | String | No | Sets the PropagateID field in the AIGC watermark, uniquely identifying a specific propagation action. Takes effect only when enable_aigc_tag is true.Default value: The request ID of the current speech synthesis request.Only cosyvoice-v3-flash, cosyvoice-v3-plus, cosyvoice-v2 support this feature. aigc_propagate_id using the HttpSpeechSynthesisParam instance's parameter method or parameters method: |
hot_fix | Map | No | Text hot-fix configuration. Customizes the pronunciation of specified words or substitutes text before speech synthesis. Not supported by cosyvoice-v2.
hot_fix using the HttpSpeechSynthesisParam instance's parameter method or parameters method: |
enable_markdown_filter | boolean | No | Only cloned voices of cosyvoice-v3-flash support this feature.
enable_markdown_filter using the HttpSpeechSynthesisParam instance's parameter method or parameters method: |
Code examples
The following examples show non-streaming and streaming calls using the CosyVoice speech synthesis API. Before running the examples, set the DASHSCOPE_API_KEY environment variable.
Each model version requires a matching voice. For example,
cosyvoice-v3-flash and cosyvoice-v3-plus use voices such as longanyang, while cosyvoice-v2 uses voices such as longxiaochun_v2. When switching models, switch to a compatible voice. Each voice also supports specific languages. When synthesizing non-Chinese text, select a voice that supports the target language. For the complete model-to-voice mapping, see CosyVoice Voice list.- Non-streaming
- Streaming
Non-streaming calls wait for synthesis to complete, then return the full result. Two return types are available:
callAndReturnAudio(): Returns audio binary data (ByteBuffer). Use this to save or process the audio directly.call(): Returns an audio URL. Use this to download the audio from a URL.