前言
为了方便学习,为了方便背诵考研政治所有想到了录音政治内容,然后反复听,以达到背诵的效果,但是日常生活中,找到一个安静的地方,有时候也不是那么容易,又或者觉得自己的声音不好听,所以特意写了这个文档转音频的代码,用于考研人。
考研时间有限
本来是准备做成exe可执行程序的但是,一直显示模块没用加载,耗费我巨额时间,所以干脆把源码丢出来,大伙有兴趣自己去转成exe文件。
import os
import pyttsx3
import re
#文件库
import tkinter as tk
from tkinter import filedialog
#docx文件处理
import docx
from docx import Document
def savetheaudio(Folderpath,Filepath,shotname,ratex,extension):
engine = pyttsx3.init()
# 获取当前语音速率
rate = engine.getProperty('rate')
print(f'语音速率:{rate}')
# 设置新的语音速率
engine.setProperty('rate', ratex)
if(extension=='.txt'):
with open(Filepath,encoding='utf-8') as f:
strx=f.read()
f.close()
else:
f = docx.Document(Filepath)
strx=''
for para in f.paragraphs:
strx =strx+para.text
engine.say(strx)
engine.save_to_file(strx,Folderpath+'/'+shotname+'.mp3')
engine.runAndWait()
print("文件存放位置:"+Folderpath+'/'+shotname+'.mp3')
def openfileandjudgement():
root=tk.Tk()
root.withdraw()
Folderpath = filedialog.askdirectory() #获得选择好的文件夹
Filepath = filedialog.askopenfilename() #获得选择好的文件
(filepath,tempfilename) = os.path.split(Filepath);
(shotname,extension) = os.path.splitext(tempfilename);
return Filepath ,shotname ,extension ,Folderpath
if __name__ == '__main__':
#批量处理
num=int(input("要处理的文件个数"))
ratex=int(input("请输入语速建议在200左右"))
for i in range(num):
Filepath ,shotname ,extension ,Folderpath = openfileandjudgement()
savetheaudio(Folderpath,Filepath,shotname,ratex,extension)
一些解式性的内容也可参考我的百度AI创建的内容
https://aistudio.baidu.com/aistudio/projectdetail/1785179?shared=1