微软Azure文本转音频,保存成MP3文件【代码python3】


标签: 文本转音频并保存mp3文件; 微软Azure;


微软Azure可以将文本转音频,并保存mp3文件,直接上代码

代码格式:python 3

python 复制代码
import os
import azure.cognitiveservices.speech as speechsdk

# This example requires environment variables named "SPEECH_KEY" and "SPEECH_REGION"
speech_config = speechsdk.SpeechConfig(subscription=os.environ.get('SPEECH_KEY'), region=os.environ.get('SPEECH_REGION'))

# The language of the voice that speaks.
speech_config.speech_synthesis_voice_name='zh-CN-YunjianNeural'   # 这个男声 有 磁性
text = "讲一个笑话:和朋友去饭店吃饭,要了一盘红烧肉,结果发现怎么咬都咬不动,我顿时就火了,把服务员叫过来喊道:你们这肉怎么咬都咬不动,把你们经理叫来。服务员说:叫我们经理干啥啊,你都咬不动,他能咬得动啊!"
speech_config.set_speech_synthesis_output_format(speechsdk.SpeechSynthesisOutputFormat.Audio24Khz160KBitRateMonoMp3) # 这里配置文件为mp3格式,要保存其它文件格式,修改这里参数
speech_synthesizer = speechsdk.SpeechSynthesizer(speech_config=speech_config, audio_config=None)

result = speech_synthesizer.speak_text_async(text).get()
stream = speechsdk.AudioDataStream(result)
stream.save_to_wav_file("D:/file.mp3")  # mp3文件保存路径


if result.reason == speechsdk.ResultReason.SynthesizingAudioCompleted:
    print("Speech synthesized Completed,  for text [{}]".format(text))
elif result.reason == speechsdk.ResultReason.Canceled:
    cancellation_details = result.cancellation_details
    print("Speech synthesis canceled: {}".format(cancellation_details.reason))
    if cancellation_details.reason == speechsdk.CancellationReason.Error:
        if cancellation_details.error_details:
            print("Error details: {}".format(cancellation_details.error_details))
            print("Did you set the speech resource key and region values?")

注意:

1,代码运行前,SPEECH_KEY和SPEECH_REGION已生成好,并保存在你的环境变量中。 参考:https://learn.microsoft.com/zh-cn/azure/ai-services/speech-service/get-started-text-to-speech?tabs=windows%2Cterminal&pivots=programming-language-javascript#prerequisites

2,python 要求3.7以上。

参考:

微软Azure Python 示例代码
https://learn.microsoft.com/zh-cn/azure/ai-services/speech-service/get-started-text-to-speech?tabs=windows%2Cterminal&pivots=programming-language-python#prerequisites

支持不同的语音和声音形式(男声、女声)
https://learn.microsoft.com/zh-cn/azure/ai-services/speech-service/language-support?tabs=tts


作者简介:https://shimo.im/docs/rp3OVwxle2fJn7Am/

上海徐汇

2023年10月29日


相关推荐
别动我齐刘海几秒前
ROS2 Jazzy + C++ 实战路线——基础学习1
c++·vscode·python·ubuntu·机器学习·自动驾驶·github
life码农8 分钟前
python框架Flask多语言配置示例
python·flask
苏离~Hack15 分钟前
SL-crawler:一个可视化配置的通用网页与 API 数据采集工具
python
小白学大数据20 分钟前
Python 小工具实战:用问财接口搭建金融数据采集器
开发语言·人工智能·python
青少儿编程课堂32 分钟前
多源最短路与最小环(Floyd 算法图论解析)
c++·python·算法·bfs·信息学竞赛
PiaoKe___33 分钟前
从端云解耦到可编程 Android 实例:云手机架构解析与 Python 批量管控实战
arm开发·python·架构·自动化
计算机源码社1 小时前
基于Hadoop+Spark的商家优惠券营销效果数据分析与可视化-基于Python的商家优惠券营销效果检测与评估分析系统
大数据·hadoop·python·数据挖掘·spark·毕业设计·数据可视化
vicky05173 小时前
解决 ModuleNotFoundError: No module named ‘torch‘ 笔记
python
wuyk5553 小时前
Python实战项目02:学生成绩管理系统(控制台|CSV导出|完整落地)
开发语言·python
qq5918406859 小时前
uiautomator2自动化安卓手机操作
python