01_pyttsx3_将文本文字转为语音播放
pyttsx3 模块可以将文字转为语音播放 支持中文播放, 音速调节
1.安装pyttsx3的库
pip install pyttsx3
2.朗读中文:
import pyttsx3 msg = '''盼望着,盼望着,东风来了,春天的脚步...''' teacher = pyttsx3.init() teacher.say(msg) teacher.runAndWait()
3.调准语速
import pyttsx3 msg = '''盼望着,盼望着,东风来了,春天的脚步...''' teacher = pyttsx3.init() rate = teacher.getProperty('rate') teacher.setProperty('rate', rate + 20)#调准语速 teacher.say(msg) teacher.runAndWait()
4.切换音色(两者都是女音,个人感觉差不多)
import pyttsx3 engine = pyttsx3.init() voices = engine.getProperty('voices') print(len(voices)) for voice in voices: engine.setProperty('voice', voice.id) engine.say('I will always love you ') engine.runAndWait()
其实可以使用 检测是否有语音功能(pywin32 )
#利用pywin32模块,来实现微软的语音接口调用
#安装pip3 install pywin32
import win32com.client
#微软这个服务器
speaker = win32com.client.Dispatch("SAPI.SpVoice")
speaker.Speak("断剑重铸之日,骑士归来之时")
爬虫读取数据
from urllib import request import time import pyttsx3 from lxml import etree #小说《大医凌然》 志鸟村 著 url = 'https://read.qidian.com/chapter/Y8j5WWawoqd1C4AOuV6yIg2/oG-HexlEuhG2uJcMpdsVgA2' headers = { "Referer": "https://read.qidian.com/", "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36" } req = request.Request(url=url,headers=headers) response = request.urlopen(req) content = response.read().decode() #复制html中的文本的XPath ##//*[@id="chapter-406583253"]/div/div[2]/p[1] # print(content) xpath_content = etree.HTML(content) new_content = xpath_content.xpath('//*[@id="chapter-406583253"]/div/div/p/text()') #print(new_content) with open('3.txt','w',encoding='utf-8') as f: for i in new_content: f.writelines(i.strip()) f.writelines('\n') time.sleep(2) with open('3.txt','r',encoding='utf-8') as f: line = f.read() engine = pyttsx3.init() volume=engine.getProperty('volume') engine.setProperty('volume', volume + 0.25) engine.say(line) engine.runAndWait()