当前位置:   article > 正文

【Python】PC听书工具,微软tts朗读_edgetts python

edgetts python

简介:

使用edge-tts朗读txt文本。拥有“断点续读”的功能。会缓存一大堆的mp3文件,可以手动清理,也可以动手合成一个音频发b站之类的。: )

20231205更新:

现在把源码上传到gitee了,方便手机用termux时克隆代码到本地。txtReader: termux 上使用 或 windows 上使用的 txt阅读器 (gitee.com)

git clone https://gitee.com/harryxiaocn/txt-reader.git

20230921更新:

为了避免缓存不够,听起来断断续续的,现在三线程同时下载音频……

源码(已过期,以仓库内源码为准):

  1. # coding=utf-8
  2. import json
  3. import os.path
  4. import threading
  5. import time
  6. import edge_tts as et
  7. from playsound import playsound
  8. import asyncio
  9. """
  10. 准备工作:
  11. 1、pip3 install edge_tts
  12. 2、pip3 install playsound
  13. """
  14. def RTxt(path):
  15. with open(path, encoding='utf8') as f:
  16. return f.read()
  17. def WTxt(path, content):
  18. with open(path, 'w', encoding='utf8') as f:
  19. f.write(content)
  20. class Reader:
  21. def __init__(self, txtPath):
  22. self.novel = RTxt(txtPath)
  23. self.novelName = os.path.basename(txtPath).split('.')[0]
  24. self.lines = self.novel.split('\n')
  25. self.setting = {'pos': 0, 'downloadPos': 0}
  26. self.sayProcess = None
  27. if os.path.exists('setting.json'):
  28. self.setting = json.loads(RTxt('setting.json'))
  29. self.end = False
  30. def Start(self):
  31. def Download():
  32. while self.setting['downloadPos'] < len(self.lines):
  33. line = self.lines[self.setting['downloadPos']]
  34. try:
  35. self.Download(line)
  36. except Exception as e:
  37. print('Download.e=', e, self.setting['downloadPos'])
  38. WTxt('setting.json', json.dumps(self.setting))
  39. while self.setting['downloadPos'] > self.setting['pos'] + 300:
  40. time.sleep(1)
  41. def Say():
  42. while self.setting['pos'] < len(self.lines):
  43. while self.setting['downloadPos'] < self.setting['pos'] + 10:
  44. print('等待缓存中……')
  45. time.sleep(1)
  46. # print('下载行=', self.setting['downloadPos'])
  47. # print('朗读行=', self.setting['pos'])
  48. print('朗读行=', self.lines[self.setting['pos']], self.setting['pos'], self.setting['downloadPos'])
  49. self.Say()
  50. self.setting['pos'] += 1
  51. downloadThread = threading.Thread(target=Download, daemon=True)
  52. downloadThread.start()
  53. downloadThread2 = threading.Thread(target=Download, daemon=True)
  54. downloadThread2.start()
  55. downloadThread3 = threading.Thread(target=Download, daemon=True)
  56. downloadThread3.start()
  57. sayThread = threading.Thread(target=Say, daemon=True)
  58. sayThread.start()
  59. sayThread.join()
  60. def Download(self, text, voice='zh-CN-YunxiNeural', rate='+25%', volume='+0%'):
  61. mp3Path = 'temp\\{}_{}.mp3'.format(self.novelName, self.setting['downloadPos'])
  62. try:
  63. self.setting['downloadPos'] += 1
  64. async def Do():
  65. await t.save(mp3Path)
  66. t = et.Communicate(text=text, voice=voice, rate=rate, volume=volume)
  67. asyncio.run(Do())
  68. except Exception as e:
  69. print('[error]Download.e=', e, mp3Path)
  70. def Say(self):
  71. """朗读"""
  72. mp3Path = 'temp\\{}_{}.mp3'.format(self.novelName, self.setting['pos'])
  73. if os.path.exists(mp3Path) and os.path.getsize(mp3Path) > 0:
  74. try:
  75. playsound('{}\\{}'.format(os.getcwd(), mp3Path))
  76. except Exception as e:
  77. print('[error]Say.e=', e)
  78. if __name__ == '__main__':
  79. reader = Reader('小说.txt')
  80. reader.Start()
  81. print('程序终止!')

暂停之类的功能实现起来比较麻烦,就没弄了。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/464832
推荐阅读
相关标签
  

闽ICP备14008679号