源: https://www.cnblogs.com/qq21270/p/7899622.html
- 英文文本转化成语音:
pyttsx 是Python的一个关于文字转语音方面的很不错的库。我们还可以借助pyttsx来实现在线朗读rfc文件或者本地文件等等,最为关键的是,它对中文支持的还是不错的。
这个试了一下,python3要用 pyttsx3 这个库(不要用pyttsx),但是中文支持有问题. 参考:http://www.cnblogs.com/leenid/p/6875031.html
import pyttsx3
engine = pyttsx3.init()
engine.say('Hello, good morning')
engine.runAndWait()
从文本文件中读取:
# -*- coding: utf-8 -*-
import pyttsx3
f = open("all.txt",'r')
line = f.readline()
engine = pyttsx3.init()
while line:
line = f.readline()
print(line, end = '')
engine.say(line)
engine.runAndWait()
- 用百度ai,把文字转换为mp3:
from aip import AipSpeech
""" 你的百度 APPID AK SK
https://console.bce.baidu.com/ai/#/ai/speech/app/list 应用列表
http://ai.baidu.com/docs#/TTS-Online-Python-SDK/top API
"""
APP_ID = '略'
API_KEY = '略'
SECRET_KEY = '略'
client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)
text111 = "春江潮水连海平 海上明月若潮升。"
result = client.synthesis(text111, 'zh', 1, {
'vol': 5,
})
# 识别正确返回语音二进制 错误则返回dict 参照下面错误码
if not isinstance(result, dict):
with open('auido.mp3', 'wb') as f:
f.write(result)
然后用os自带的播放器播放:
import os
os.system('/usr/bin/totem /home/allen/auido.mp3')
或用pygame播放mp3文件: (不过声音有点失真,有点娃娃气)
import time
import pygame
file = r'auido.mp3'
pygame.mixer.init()
print("播放音乐1")
track = pygame.mixer.music.load(file)
pygame.mixer.music.play()
time.sleep(10)
pygame.mixer.music.stop()
播放mp3文件,还有一个windows上的极简野蛮操作:
import time
import os
os.system("zz.mp3")
time.sleep(10)
os.system("taskkill /F /IM wmplayer.exe")