小工具知识网

当前位置: 首页 > 行业知识 > PySimpleGUI 综合应用|英语文本朗读以及转换为语音Mp3

行业知识

PySimpleGUI 综合应用|英语文本朗读以及转换为语音Mp3

2026-10-23 10:02:26 来源:互联网转载

PySimpleGUI 综合应用

���录

PySimpleGUI 综合应用

应用界面

完整代码

所需模块

PySimpleGUI

pyttsx3

pyaudio

rapidfuzz

字典格式


应用界面

完整代码

英语朗读器.pyw

import PySimpleGUI as sgimport pyttsx3,pyaudio,pyperclipimport os,re,datetime,wave,threadingfrom rapidfuzz import fuzzclass AudioPlayer(threading.Thread):    def __init__(self, filename):        super().__init__()        self.filename = filename        self.st, self.pa, self.wf = None, None, None        self.stop_event = threading.Event()    def run(self):        self.wf = wave.open(self.filename, 'rb')        self.pa = pyaudio.PyAudio()        self.st = self.pa.open(format=self.pa.get_format_from_width(self.wf.getsampwidth()),                channels=self.wf.getnchannels(), rate=self.wf.getframerate(), output=True)        data = self.wf.readframes(1024)        while not self.stop_event.is_set() and len(data) > 0:            self.stop_event.wait(0.01)  # 检查停止事件(非阻塞)            if not self.stop_event.is_set():                self.st.write(data)            data = self.wf.readframes(1024)        if self.st:            self.st.stop_stream()            self.st.close()        if self.pa:            self.pa.terminate()    def stop(self):        self.stop_event.set()  # 设置停止标志def loadSentence(file):    res = [],[]    try:        with open('en'+file+'.txt','r',encoding='utf-8') as f:            text = f.readlines()            for txt in text:                if txt.count('|')!=1: continue                if txt.endswith('\n'): txt=txt[:-1]                for i,t in enumerate(txt.split('|')):                    res[i].append(t)        return res    except:        sg.popup_error(f'文件[{file}]不存在,程序无法运行!', font=txFont, title='Error')        return None,def engineSay(txt):    engine.say(txt)    engine.runAndWait()def engineFile(txt, mp3File):    try:        if os.path.exists(mp3File):            os.remove(mp3File)        widgetDisabled(['朗读列表'])        showMessage('语音文件生成中,请稍候......')        audio = engine.save_to_file(txt, mp3File)        engine.runAndWait()        showMessage('朗读中......')        widgetDisabled(['停止播放'], False)        window.Refresh()        return True    except:        sg.popup_error('生成语音文件失败,无法朗读!', font=txFont, title='Error')        return Falsedef stringSize(s):    return len(s)+len([c for c in s if '\u4e00'

上一篇:服务器系统怎么调亮度的?

下一篇:Win10账户切换详解,轻松掌握多账户切换技巧!