python借用百度大脑把文字转换成音频文件

python借用百度大脑把文字转换成音频文件

======================

今天用python写了一个简单的程序把文字转换成语音,以下是代码

from aip import AipSpeech

class Ai:
    APP_ID = '11766958'
    API_KEY = 'USWmlsBc2zxv9rcNN2gNPb9H'
    SECRET_KEY = 'GxF8tOEO2MbkM6qPtHbF9wZhYPQc6zt7'
    def __init__(self,msg_file,out_file="audio.mp3"):
        self.msg_file=msg_file
        self.out_file=out_file

    def text2audio(self):
        # 把txt文件转成音频文件
        # msg_file是txt文件名
        # out_file是音频文件名。
        with open(self.msg_file,"r") as file:
            text=file.read()
        client = AipSpeech(self.APP_ID, self.API_KEY, self.SECRET_KEY)
        for i in range(int(len(text)/500)+1):
            result  = client.synthesis(text[i:i+500], 'zh', 1, {
                "spd":5,
                'vol':5,
                "per":4,
        })
            if not isinstance(result, dict):
                with open(self.out_file, 'ab') as f:
                    f.write(result)
        print("处理完毕!")



if __name__ == '__main__':
    msg_file="msg.txt"
    ai=Ai(msg_file)
    ai.text2audio()

当然也可以写一个类来把文字转成语音。这是另一种实现文字转语音的方法。

python借用百度大脑把文字转换成音频文件_第1张图片

你可能感兴趣的:(python)