我有一个需要在Windows Media Player中打开文件的程序,因为在文件完成后,它需要杀死wmplayer.exe。我尝试过使用subprocess.Popen(["C:\Program Files (x86)\Windows Media Player\wmplayer.exe", my_file])
和subprocess.call(["C:\Program Files (x86)\Windows Media Player\wmplayer.exe", my_file])
,但这只是打开Windows Media Player;不是我要打开的特定文件。 (my_file变量存储.mp3文件的路径(它与.py文件位于同一文件夹中),并在我在代码中使用它的其他地方工作,当我使用webbrowser.open
时)。< / p>
完整代码:
try:
import webbrowser
import os
import time
import sys
import getpass
import pip
import subprocess
from contextlib import contextmanager
@contextmanager
def suppress_stdout():
with open(os.devnull, "w") as devnull:
old_stdout = sys.stdout
sys.stdout = devnull
try:
yield
finally:
sys.stdout = old_stdout
with suppress_stdout():
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
my_file = "Text To Speech.mp3"
username = getpass.getuser()
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.call(["C:\Program Files (x86)\Windows Media Player\wmplayer.exe", my_file])
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: """)
def text_to_speech():
while True:
audio = MP3(my_file)
audio_length = audio.info.length
time.sleep((audio_length) + 0.25)
os.system('TASKKILL /F /IM wmplayer.exe')
time.sleep(0.5)
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: """)
return text_to_speech()
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.""")
text_to_speech()
except KeyboardInterrupt:
check_and_remove_file()
print("""
Goodbye!""")
sys.exit()
是否有人知道如何确保使用Windows Media Player打开该特定文件,而不仅仅是Windows Media Player?
答案 0 :(得分:1)
WMP可能希望播放媒体的完整路径并且不关心脚本执行的位置。尝试:
wmp = r"C:\Program Files (x86)\Windows Media Player\wmplayer.exe"
media_file = os.path.abspath(os.path.realpath(my_file))
subprocess.call([wmp, media_file])
答案 1 :(得分:-1)
如果将Windows Media Player设置为.mp3文件调用的默认播放器
os.startfile(path_to_your_mp3)
应该有用。