当前位置: 首页 > news >正文

科大讯飞在线语音合成(流式版)python版

1、进入自己的项目

复制APPID、APISecret、APIKey

2、添加好听发音人

复制vcn参数

3、需要替换代码部分:

换自己喜欢的发声人的参数

换上自己的APPID、APISecret、APIKey

4、完整代码:

# -*- coding:utf-8 -*-
import _thread as thread
import base64
import hashlib
import hmac
import wave
import json
import os
import ssl
from datetime import datetime
from time import mktime
from urllib.parse import urlencode
import websocketclass Ws_Param:def __init__(self, APPID, APIKey, APISecret, Text):self.APPID = APPIDself.APIKey = APIKeyself.APISecret = APISecretself.Text = Textself.CommonArgs = {"app_id": self.APPID}self.BusinessArgs = {"aue": "raw", "auf": "audio/L16;rate=16000", "vcn": "x4_lingyuyan", "tte": "utf8"}self.Data = {"status": 2, "text": str(base64.b64encode(self.Text.encode('utf-8')), "UTF8")}def create_url(self):url = 'wss://tts-api.xfyun.cn/v2/tts'date = datetime.now().strftime("%a, %d %b %Y %H:%M:%S GMT")signature_origin = f"host: ws-api.xfyun.cn\ndate: {date}\nGET /v2/tts HTTP/1.1"signature_sha = hmac.new(self.APISecret.encode('utf-8'), signature_origin.encode('utf-8'),hashlib.sha256).digest()signature_sha = base64.b64encode(signature_sha).decode()authorization_origin = f"api_key=\"{self.APIKey}\", algorithm=\"hmac-sha256\", headers=\"host date request-line\", signature=\"{signature_sha}\""authorization = base64.b64encode(authorization_origin.encode('utf-8')).decode()v = {"authorization": authorization, "date": date, "host": "ws-api.xfyun.cn"}return url + '?' + urlencode(v)def on_message(ws, message):try:message = json.loads(message)code = message.get("code")if code != 0:print(f"错误:{message.get('message')},代码:{code}")returnaudio = base64.b64decode(message["data"].get("audio", b""))with open(output_pcm, 'ab') as f:f.write(audio)if message["data"].get("status") == 2:print("WebSocket连接已关闭。")ws.close()except Exception as e:print("处理消息时出错:", e)def on_error(ws, error):print("WebSocket错误:", error)def on_close(ws, close_status_code, close_msg):print(f"WebSocket关闭,状态码:{close_status_code},关闭信息:{close_msg}")def on_open(ws):def run():ws.send(json.dumps({"common": wsParam.CommonArgs, "business": wsParam.BusinessArgs, "data": wsParam.Data}))if os.path.exists(output_pcm):os.remove(output_pcm)thread.start_new_thread(run, ())if __name__ == "__main__":input_txt = "在时光长河的悄然流淌里,命运的丝线将你我缠绕。还记得初次相遇,阳光正好,你就那样带着一身光芒,不经意间走进了我的视线,从此,我的目光便再也无法从你身上移开。"output_pcm = "output.pcm"output_wav = "output.wav"wsParam = Ws_Param(APPID='###', APISecret='###',APIKey='###', Text=input_txt)ws = websocket.WebSocketApp(wsParam.create_url(), on_message=on_message, on_error=on_error, on_close=on_close)ws.on_open = on_openwebsocket.enableTrace(False)ws.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE})with open(output_pcm, 'rb') as pcmfile:pcmdata = pcmfile.read()with wave.open(output_wav, 'wb') as wavfile:wavfile.setparams((1, 2, 16000, 0, 'NONE', 'NONE'))wavfile.writeframes(pcmdata)print("转换完成。")

3、播放MAV文件

from playsound import playsound# 播放 WAV 文件
playsound("output.wav")

4、转MP3文件

from pydub import AudioSegmentsong = AudioSegment.from_wav("output.wav")
song.export("demo.mp3", format="mp3")

感谢您的支持和关注!!!

http://www.lryc.cn/news/511666.html

相关文章:

  • 常见搜索算法汇总
  • vue 中 ref 详解
  • 探索开源项目 kernel:技术的基石与无限可能
  • C 实现植物大战僵尸(二)
  • Vivado - TCL 命令(DPU脚本、v++命令、impl策略)
  • 【JDBC】数据库连接的艺术:深入解析数据库连接池、Apache-DBUtils与BasicDAO
  • hadoop-common的下载位置分享
  • 【机器学习】SVM支持向量机(一)
  • Spring Boot介绍、入门案例、环境准备、POM文件解读
  • 基于Spring Boot + Vue3实现的在线商品竞拍管理系统源码+文档
  • LeetCode--排序算法(堆排序、归并排序、快速排序)
  • 华诺星空 Java 开发工程师笔试题 - 解析
  • QT:一个TCP客户端自动连接的测试模型
  • 关于启动vue项目,出现:Error [ERR_MODULE_NOT_FOUND]: Cannot find module ‘xxx‘此类错误
  • 电路元件与电路基本定理
  • 指针之矢:C 语言内存幽境的精准飞梭
  • uniapp下载打开实现方案,支持安卓ios和h5,下载文件到指定目录,安卓文件管理内可查看到
  • 免费干净!付费软件的平替款!
  • 软路由系统 iStoreOS 中部署 Minecraft 服务器
  • 第 29 章 - ES 源码篇 - 网络 IO 模型及其实现概述
  • 细说STM32F407单片机IIC总线基础知识
  • 从头开始学MyBatis—04缓存、逆向工程、分页插件
  • Artec Space Spider助力剑桥研究团队解码古代社会合作【沪敖3D】
  • 《探索PyTorch计算机视觉:原理、应用与实践》
  • 【C#设计模式(21)——状态模式(State Pattern)】
  • nvm日常使用中常用命令总结
  • 【数据仓库】SparkSQL数仓实践
  • PessimisticLock
  • 【Maven】属性管理
  • 微信小程序性能优化、分包