Overview and SDK Code Examples

Updated at:

The CosyVoice voice cloning service uses a large model to extract voice features from audio and generate a custom voice without training. This topic describes the requirements for voice cloning and provides Python and Java SDK examples for cloning and querying voices, followed by instructions for using cloned voices in speech synthesis.

Important

The voice cloning service was upgraded to CosyVoice 2.0 on April 14, 2025. Voices cloned after the upgrade use CosyVoice 2.0 by default, which provides better cloning results than version 1.0.

Voices previously cloned with CosyVoice 1.0 remain available. You can also clone them again from the original audio to improve the results.

Use cases

  • Companionship: Use a cloned family member's voice in smart assistants, in-vehicle navigation, and home entertainment, such as reading picture books, controlling appliances, or providing educational guidance.

  • Education: Use a cloned teacher's voice to support teacher-student interaction and enrich instructional videos and course materials with a familiar voice.

  • Audio and video production: Clone a presenter's voice for additional recordings and dubbing during post-production.

  • Intelligent customer service: Use a cloned account manager's voice to personalize services such as customer follow-up and marketing calls.

Benefits

  • Short audio samples: Clone a voice from a recording that is only 10 to 20 seconds long.

  • Voice reproduction: CosyVoice combines a generative neural network speech model developed by Alibaba Qwen Speech Lab with zero-shot learning to reproduce a person's intonation, rhythm, and emotional expression.

  • Instant synthesis: Reproduce a voice in seconds with real-time voice cloning.

Usage notes

  • Voice quota and retention: Each UID can clone up to 1,000 voices. Versions v1 and v2 share this quota. Voices that have not been used for more than one year are taken offline. Deleting cloned voices is not currently supported.

  • Copyright and legal use: You are responsible for the ownership and legal use rights of the voices you provide. Before activating Streaming Text-to-Speech in Intelligent Speech Interaction, read the service agreement.

  • Using cloned voices: Cloned voices (VoiceName) are used in the same way as CosyVoice preset voices, such as longxiaoxia. For details, see the CosyVoice speech synthesis API reference.

    Important

    CosyVoice cloned voices can be used only with CosyVoice speech synthesis. Synthesis fails if they are used with other speech synthesis services.

  • Access method: The voice cloning service currently supports API calls only.

Billing

Voice cloning is free of charge. After cloning a voice, using it for text-to-speech incurs CosyVoice speech synthesis API charges, currently CNY 2 per 10,000 characters. For details, see Billing methods.

Prerequisites

  • Review the applicable terms and activate the Commercial Edition of Streaming Text-to-Speech on the Intelligent Speech Interaction activation page.

  • Prepare a publicly accessible audio URL. We recommend uploading the audio to OSS. For instructions, see Simple upload. The audio requirements are as follows:

    • Channels: mono or stereo

    • Bit depth: 16 bit

    • Sample rate: greater than 16,000 Hz

    • Format: WAV, MP3, or M4A

    • File size: no more than 10 MB

    • Duration: 10 to 20 seconds. Recordings longer than 60 seconds are not recommended. Speak fluently and include at least one segment of continuous speech longer than 5 seconds.

SDK examples

The following examples call the voice cloning API using the Python and Java SDKs. Before running an example, set the ALIYUN_AK_ID and ALIYUN_AK_SECRET environment variables to your AccessKey ID and AccessKey secret, respectively. Replace the audio URL in the example with the publicly accessible URL you prepared.

Python

Step 1: Install the SDK

Install the Alibaba Cloud SDK for Python.

pip install aliyun-python-sdk-core

Step 2: Clone and query voices

Use the following code to call the voice cloning API:

import os
import json
import time

from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.request import CommonRequest

# Read the AccessKey ID and AccessKey secret from environment variables.
client = AcsClient(os.environ.get('ALIYUN_AK_ID'), os.environ.get('ALIYUN_AK_SECRET'))
domain = 'nls-slp.cn-shanghai.aliyuncs.com'
version = '2019-08-19'

def build_request(api_name, method):
    request = CommonRequest()
    request.set_domain(domain)
    request.set_version(version)
    request.set_action_name(api_name)
    request.set_method(method)
    request.set_protocol_type('https')
    return request

def cosy_clone(voice_prefix, url):
    clone_request = build_request('CosyVoiceClone', 'POST')
    clone_request.add_body_params('Url', url)
    clone_request.add_body_params('VoicePrefix', voice_prefix)
    # Set the read timeout to 15 seconds.
    clone_request.set_read_timeout(15)
    begin = int(round(time.time() * 1000))
    clone_response = client.do_action_with_exception(clone_request)
    end = int(round(time.time() * 1000))
    print(json.loads(clone_response))
    print('cost: {}'.format(end - begin))

def cosy_list(voice_prefix, page_index=1, page_size=10):
    list_request = build_request('ListCosyVoice', 'POST')
    list_request.add_body_params('VoicePrefix', voice_prefix)
    list_request.add_body_params('PageIndex', page_index)
    list_request.add_body_params('PageSize', page_size)
    list_response = client.do_action_with_exception(list_request)
    print(json.loads(list_response))

if __name__ == '__main__':
    # 1. Call CosyVoiceClone to clone a voice.
    audio_url = 'https://your-url'
    prefix = 'tongyi'  # Use letters or digits.
    cosy_clone(prefix, audio_url)
    # A successful call synchronously returns VoiceName in the format
    # cosyvoice-${voice_prefix}-${7 random characters}.

    # 2. Call ListCosyVoice to query voice statuses for the specified prefix.
    cosy_list(prefix)

For more information, see the CosyVoice voice cloning API.

Step 3: Use the cloned voice

When calling CosyVoice speech synthesis, set the voice field to the VoiceName returned by voice cloning. For details, see the CosyVoice speech synthesis API reference.

Java

Step 1: Install the SDK

Add the following dependency to your Maven project. This example uses aliyun-java-sdk-core 4.6.4.

<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>aliyun-java-sdk-core</artifactId>
    <version>4.6.4</version>
</dependency>

Step 2: Clone and query voices

Use the following code to call the voice cloning API:

package org.example;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.profile.DefaultProfile;

public class CosyVoiceDemo {
    // Endpoint
    private static final String DOMAIN = "nls-slp.cn-shanghai.aliyuncs.com";
    // API version
    private static final String API_VERSION = "2019-08-19";

    private static final IAcsClient client;

    static {
        // Create and initialize the DefaultAcsClient instance.
        DefaultProfile profile = DefaultProfile.getProfile(
                "cn-shanghai",
                // Read the AccessKey ID and AccessKey secret from environment variables.
                System.getenv("ALIYUN_AK_ID"),
                System.getenv("ALIYUN_AK_SECRET"));
        client = new DefaultAcsClient(profile);
    }

    public static void main(String[] args) throws InterruptedException {
        String voicePrefix = "tongyi";
        String url = "your-file-url";
        cosyClone(voicePrefix, url);
        cosyList(voicePrefix);
    }

    private static void cosyList(String voicePrefix) {
        CommonRequest request = buildRequest("ListCosyVoice");
        request.putBodyParameter("VoicePrefix", voicePrefix);
        String response = sendRequest(request);
        System.out.println(response);
    }

    private static void cosyClone(String voicePrefix, String url) {
        CommonRequest cloneRequest = buildRequest("CosyVoiceClone");
        cloneRequest.putBodyParameter("VoicePrefix", voicePrefix);
        cloneRequest.putBodyParameter("Url", url);
        // Set the read timeout to 15 seconds.
        cloneRequest.setSysReadTimeout(15000);
        long startTime = System.currentTimeMillis();
        String response = sendRequest(cloneRequest);
        long endTime = System.currentTimeMillis();
        System.out.println(response);
        System.out.println("cost: "+ (endTime - startTime) + " ms");
    }

    private static CommonRequest buildRequest(String popApiName) {
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain(DOMAIN);
        request.setVersion(API_VERSION);
        request.setAction(popApiName);
        request.setProtocol(ProtocolType.HTTPS);
        return request;
    }

    private static String sendRequest(CommonRequest request) {
        try {
            CommonResponse response = client.getCommonResponse(request);
            return response.getData();
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return null;
    }
}

For more information, see the CosyVoice voice cloning API.

Step 3: Use the cloned voice

When calling CosyVoice speech synthesis, set the voice field to the VoiceName returned by voice cloning. For details, see the CosyVoice speech synthesis API reference.

Status codes

Status code

Status message

Cause and solution

40001000

QUOTA_ERROR

Check whether the service is activated.

40001001

VOICE_LIMIT_ERROR

The number of cloned voices exceeds the limit. The default limit is 1,000.

40001002

VOICE_PREFIX_ERROR

The voice name prefix does not meet the following requirements:

  • It must not be empty.

  • It must be no longer than 10 characters.

  • It must contain only digits and letters.

40002000

AUDIO_URL_ERROR

The audio URL is invalid.

40002001

AUDIO_DOWNLOAD_FAIL

Failed to download the audio.

40002002

FILE_SIZE_EXCEED

The audio file exceeds 10 MB.

40002003

AUDIO_SAMPLE_RATE_ERROR

The audio sample rate is less than 16 kHz.

40002004

AUDIO_FORMAT_ERROR

The audio format is incorrect and decoding failed. The supported formats are wav, mp3, m4a, and aac.

40003000

SILENT_AUDIO_ERROR

The audio does not contain enough valid speech.

40003001

AUDIO_SNR_ERROR

The audio signal-to-noise ratio is too low.

50000000

SERVER_ERROR

A service error occurred. Retrying the operation usually resolves the issue.

For CosyVoice voice cloning, this error usually occurs because the recording quality is poor. Follow the Recording guide to record and clone the voice again. Keep the recording as free of noise as possible, avoid frequent and unnecessary pauses, and include at least 5 seconds of continuous speech.

-

ACCESS_DENIED : Permission denied!

Permission denied.

This error occurs when a RAM user calls voice cloning without the AliyunNLSFullAccess permission. For instructions on granting permissions, see Manage RAM user permissions.

Related information