python实现语音在线合成,让你的小说自己念给你听

时间:2022-07-25
本文章向大家介绍python实现语音在线合成,让你的小说自己念给你听,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

前言

有声小说相信大家都不陌生了, 里面的音频基本都是一些声优录制的。其实除了录制音频, 咱们可以利用百度开放的api接口使用python语言在线合成语音。

制作属于自己的有声小说, 一睹为快吧!!

本文内容:

  1. 爬取指定章节的小说
  2. 调用百度api开放接口实现文字转换语音
  3. 读取文本的处理, 保存音频数据

环境介绍:

  • python 3.6
  • pycharm
  • requests
  • re
  • aip

代码

import re
import requests
from aip import AipSpeech


def get_novel(number):
    # 1、分析目标网页,确定爬取的url路径,headers参数
    url = 'http://www.xbiquge.la/10/10489/'

    # 2、发送请求 -- requests 模拟浏览器发送请求,获取响应数据
    response = requests.get(url)
    response.encoding = response.apparent_encoding  # 自动识别响应体的编码
    html_data = response.text
    # print(html_data)

    # 3、解析数据
    result_list = re.findall("<dd><a href='(.*?)' >.*</a></dd>", html_data)
    # print(result_list)

    # 为了测试只下载一个章节的小说
    sound = result_list[int(number)]
    # 构造小说内容页的网址
    all_url = 'http://www.xbiquge.la' + str(sound)
    # print(new_url)

    response_1 = requests.get(all_url)
    response_1.encoding = response.apparent_encoding
    html_data_2 = response_1.text

    result = re.findall('<div id="content">(.*?)<p>.*</p></div>', html_data_2, re.S)
    # print(result)

    # 保存数据
    with open('a.txt', mode='w', encoding='utf-8') as f:
        f.write(result[0].replace('&nbsp;', '').replace('<br/>', 'n').replace('<br />', ''))


def change_talk():
    """ 你的 APPID AK SK """
    app_id = ''
    api_key = ''
    secret_key = ''

    client = AipSpeech(app_id, api_key, secret_key)

    # 处理文本长度
    with open('a.txt', 'r', encoding='utf-8') as f:
        flag = 0
        while True:
            flag += 1
            text = f.read(1023)  # 每次读取 1024 个字节(即 1 KB)的内容
            if not text:
                break
            # print(text)
            # print('*' * 300)

            result = client.synthesis(text, 'zh', '1',
                                      {"vol": 9,
                                       "spd": 4,
                                       "pit": 9,
                                       "per": 0,
                                       })

            # 识别正确返回语音二进制 错误则返回dict 参照下面错误码
            if not isinstance(result, dict):  # 如果返回的数据不是字典, 那就是二进制音频数据
                with open('video\{}.mp3'.format(str(flag)), 'wb') as file:
                    file.write(result)
                    print('正在生成第 {} 段语音........'.format(flag))


if __name__ == '__main__':
    num = input('输入想要朗读的章节(数字):')
    get_novel(num)
    change_talk()

成果展示: