Python调用搜狗语音API实现文字转音频

搜狗语音API

https://zhiyin.sogou.com/doc/?url=/docs/content/tts/

首先打开控制台创建应用,获得APP_ID,APP_KEY,语音合成只有100万字符的免费调用。

调用示例:

import requests
import json
import os

""" 你的 APPID APPKEY """

appid = 'XXXXX'
appkey = 'XXXXXX'

# 获取token
def getToken():
	data = {
		'appid': appid,
		'appkey': appkey,
		'exp': '3600s'
	}

	headers = {'Content-Type': 'application/json'}

	r = requests.post('https://api.zhiyin.sogou.com/apis/auth/v1/create_token', data=json.dumps(data), headers=headers)
	jsonObj = json.loads(r.text)
	return jsonObj['token']

# 文字转音频
def Text2Audio(text, audiofile):
	data = {
		'input': {
			'text': text,
		},
		'config': {
			'audio_config': {
				'audio_encoding':'MP3',
				'pitch':1,
				'volume':1,
				'speaking_rate':1
			},
		'voice_config':{
			'language_code':"zh-cmn-Hans-CN",
			'speaker':'female'
			}
		}
	}

	token = getToken()

	headers = {
		'Content-Type': 'application/json',
		'Appid': appid,
		'Authorization': 'Bearer ' + token
	}

	r = requests.post('https://api.zhiyin.sogou.com/apis/tts/v1/synthesize', data=json.dumps(data), headers=headers)
	with open(audiofile, 'ab+') as f2:
		f2.write(r.content)

 

你可能感兴趣的:(Python)