Overseas access: www.kdjingpai.com
Bookmark Us
Current Position:fig. beginning " AI Answers

如何使用Python调用Qwen-TTS API生成语音?

2025-08-23 652

Python调用Qwen-TTS API的完整指南

以下是使用Python调用Qwen-TTS API的详细步骤和代码示例:

environmental preparation

  • 安装Python 3.6或以上版本
  • Install the necessary dependency libraries:
    pip install dashscope
    pip install requests
  • Ensure stable network connectivity

核心代码示例

以下是一个完整的语音合成和下载示例:

import os
import requests
import dashscope
def get_api_key():
    api_key = os.getenv("DASHSCOPE_API_KEY")
    if not api_key:
        raise EnvironmentError("DASHSCOPE_API_KEY环境变量未设置")
    return api_key
def synthesize_speech(text, voice="Dylan"):
    try:
        response = dashscope.audio.qwen_tts.SpeechSynthesizer.call(
            model="qwen-tts-latest",
            api_key=get_api_key(),
            text=text,
            voice=voice
        )
        return response.output.audio["url"]
    except Exception as e:
        raise RuntimeError(f"语音合成失败: {e}")
def download_audio(audio_url, save_path="output.wav"):
    try:
        resp = requests.get(audio_url, timeout=10)
        resp.raise_for_status()
        with open(save_path, 'wb') as f:
            f.write(resp.content)
        print(f"音频文件已保存至: {save_path}")
    except Exception as e:
        raise RuntimeError(f"下载失败: {e}")

Parameter description

  • text: 需要转换为语音的文本内容
  • voice: 语音风格,可选值包括Cherry、Ethan等7种
  • model: 指定模型版本
  • save_path: 音频文件保存路径

Recommended

Can't find AI tools? Try here!

Just type in the keyword Accessibility Bing SearchYou can quickly find all the AI tools on this site.

Top

en_USEnglish