0
私は、ユーザーの入力を求めてその入力を音声として出力するテキスト読み上げプログラムを持っています。ユーザーは、別の入力を音声に変換したいのか、プログラムを終了するのかを尋ねます。現時点では、Windows Media Playerがテキスト読み上げファイルを再生するため、プログラムはWindows上でのみ動作します。どのようにしてPython内からファイルを再生できるようにすることができますか?そして、拡張によって、すべてのオペレーティングシステムで動作しますか?コード内に他のオペレーティングシステムでの実行を妨げるような部分がある場合は、その内容と変更方法を教えてください。ありがとう!私のテキスト読み上げプログラムは、すべてのオペレーティングシステムで完全に移植可能で使用可能にするにはどうすればいいですか?
try:
import os
import time
import sys
import getpass
import pip
import subprocess
from contextlib import contextmanager
my_file = "Text To Speech.mp3"
wmp = "C:\Program Files (x86)\Windows Media Player\wmplayer.exe"
media_file = os.path.abspath(os.path.realpath(my_file))
username = getpass.getuser()
@contextmanager
def suppress_output():
with open(os.devnull, "w") as devnull:
old_stdout = sys.stdout
sys.stdout = devnull
try:
yield
finally:
sys.stdout = old_stdout
def check_and_remove_file():
if os.path.isfile(my_file):
os.remove(my_file)
def input_for_tts(message):
tts = gTTS(text = input(message))
tts.save('Text To Speech.mp3')
subprocess.Popen([wmp, media_file])
audio = MP3(my_file)
audio_length = audio.info.length
time.sleep((audio_length) + 2) # Waits for the audio to finish playing before killing it off.
os.system('TASKKILL /F /IM wmplayer.exe')
time.sleep(0.5) # Waits for Windows Media Player to fully close before carrying on.
with suppress_output():
pkgs = ['mutagen', 'gTTS']
for package in pkgs:
if package not in pip.get_installed_distributions():
pip.main(['install', package])
from gtts import gTTS
from mutagen.mp3 import MP3
check_and_remove_file()
input_for_tts("Hello there " + username + """. This program is
used to output the user's input as speech.
Please input something for the program to say: """)
while True:
answer = input("""
Do you want to repeat? (Y/N) """).strip().lower()
if answer in ["yes", "y"]:
input_for_tts("""
Please input something for the program to say: """)
elif answer in ["no", "n"]:
check_and_remove_file()
sys.exit()
else:
print("""
Sorry, I didn't understand that. Please try again with either Y or N.""")
except KeyboardInterrupt:
check_and_remove_file()
print("""
Goodbye!""")
sys.exit()
PyMediaがまだPython 3.xをサポートしていないようです。 (最新のバージョンはPython 2.7用です)。 – Gameskiller01
Pythonには多くのmp3プレーヤーがあります。これらはより良い選手ですか? http://audiotools.sourceforge.net/index.html –