作業系統:Windows 10_x64 python版本:Python 3.9.2_x64 pyttsx3版本: 2.90 pyttsx3是一個tts引擎包裝器,可對接SAPI5、NSSS(NSSpeechSynthesizer)、espeak等引擎,實作統一的tts介面,
pyttsx3的地址:https://pypi.org/project/pyttsx3/

幫助檔案地址:https://pyttsx3.readthedocs.org/
安裝pyttsx3依賴包:
pip install pyttsx3
介面介紹
1、init介面
使用的具體引擎可以在init里面指定:
pyttsx3.init([driverName : string, debug : bool]) → pyttsx3.Engine 入參: driverName : 可選,用于指定tts引擎,若未指定,則使用系統默認引擎,- sapi5 - windows環境
- nsss - Mac OS X環境
- espeak - 非windows和Mac OS X 的其它系統
2、engine介面
使用init介面初始完畢,會回傳engine物件, engine物件的方法如下:
- connect
- disconnect
- endLoop
- getProperty
- isBusy
- iterate
- runAndWait
- save_to_file
- say
- setProperty
- startLoop
- stop
使用示例
1、使用pyttsx3播放語音及生成檔案 簡單示例:#! /usr/bin/env python3 #-*- coding:utf-8 -*- # pip install pyttsx3 import pyttsx3 def onStart(name): print('starting',name) def onWord(name,location,length): print('word',name,location,length) def onEnd(name,completed): print('finishing',name,completed) engine = pyttsx3.init() # 注冊回呼函式 engine.connect('started-utterance', onStart) engine.connect('started-word', onWord) engine.connect('finished-utterance', onEnd) # 語音轉文本測驗(直接播放) engine.say("I will speak this text") engine.say('I will speak this text!', 'speak') # 注冊 speak 關鍵字,進行事件通知 engine.say("我可以說話了") # 語音轉文本測驗(檔案存盤到磁盤) engine.save_to_file('我可以說話了', 'test.mp3') # 運行并等待 engine.runAndWait()運行效果如下:
2、使用pyttsx3搭建簡單的tts服務
這里使用tornado搭建簡單的http服務(tornado是一個開源的網路服務器框架),來實作tts服務, 時序如下:
主邏輯代碼如下:
def text2File(text,dstFile): engine = pyttsx3.init() engine.save_to_file(text,dstFile) engine.runAndWait() class MainHandler(tornado.web.RequestHandler): def get(self): tmpFile = "1.mp3" print("get",self.request.arguments) text = self.get_query_argument("text").strip() print("text : %s" % text) if len(text) > 0 : text2File(text,tmpFile) self.set_header('content-type', 'audio/mpeg') fbin = open(tmpFile,"rb").read() self.set_header('Content-Length', len(fbin)) self.set_header('Content-Disposition', 'attachment;filename="%s"'%tmpFile) self.write(fbin) self.finish() else: self.set_header('content-type', 'application/json') self.finish(json.dumps({"result" : "input text "})) def post(self): print("post") print(self.request.arguments)
運行效果如下:
本文涉及資源下載地址:https://pan.baidu.com/s/1Dc8zlL2fs8p4ebF916WyXQ
可關注微信公眾號(聊聊博文)后回復 2022040401 獲得提取碼,
微信公眾號:
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/455572.html
標籤:其他
上一篇:手撕spring核心原始碼,徹底搞懂spring流程
下一篇:Spring Boot啟動流程
