考研的福音,文本转音频,支持docx,txt文件


前言

为了方便学习,为了方便背诵考研政治所有想到了录音政治内容,然后反复听,以达到背诵的效果,但是日常生活中,找到一个安静的地方,有时候也不是那么容易,又或者觉得自己的声音不好听,所以特意写了这个文档转音频的代码,用于考研人。


考研时间有限

本来是准备做成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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

阁下莫非东西

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值