嗨,我想播放mp3,但当调用的函数为logCreater时,错误显示可以加载mp3。 第一次,它可以正确播放音频,但是当它被调用时,则无法加载mp3。 错误味精说的pygame.mixer.music.load无法加载xxxxx.mp3文件 实际上,这是lil项目,而这只是其中的一个模块。 请建议我代码更正。
错误消息是:
回溯(最近通话最近): 文件“ e:\ Tutorials etc \ ProjBack \ Healthy_programmer_cli \ MainModule.py”,第151行,位于 timCount() 在timCount中的文件“ e:\ Tutorials etc \ ProjBack \ Healthy_programmer_cli \ MainModule.py”,第65行 EyeExcercise.logCreater() logCreater中的文件“ e:\ Tutorials etc \ ProjBack \ Healthy_programmer_cli \ EyeExcercise.py”,第45行 pygame.mixer.music.load(“ Eyesound.mp3”) pygame.error:无法打开'Eyesound.mp3'
import os
os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = "hide"
from os.path import expanduser
import time as t
import getpass
usernm = getpass.getuser()
from datetime import datetime
import pygame
def userDirFinder():
from os.path import expanduser
usrpth = expanduser("~")
mainp = os.path.join(usrpth, "Documents")
return mainp
def checknSetdir():
mainp=userDirFinder()
target_path = os.path.join(mainp,"HealthManger","Eye_Excercise_log")
if os.path.exists(target_path):
os.chdir(target_path)
else:
os.makedirs(target_path)
os.chdir(target_path)
def getCurrentDateandTime():
Dat = datetime.now()
currentD = Dat.strftime("%d/%m/%Y")
currentT = Dat.strftime("%I:%M %p")
return currentD , currentT
def logCreater():
print("Countdown paused")
pygame.mixer.init()
pygame.mixer.music.load("Eyesound.mp3")
pygame.mixer.music.play(-1)
write_msg = f"Eye Excercise Done by {usernm}"
while 1:
try:
print("Time for a Eye Excercise Break , After the Eye Excercise")
usr_msg = input("Type \"Done\" to stop this alarm: ")
usr_msg = usr_msg.lower()
if usr_msg != "done":
raise ValueError("Invalid Answer")
elif "done" == usr_msg:
checknSetdir()
with open("eye_excercise_log.txt","a") as fi:
cdat , ctim = getCurrentDateandTime()
fi.write(f"Date: {cdat} Time: {ctim} Message: {write_msg}\n")
# print("Log Created")
pygame.mixer.music.stop()
break
except Exception as e:
print(e)
def logReader():
try:
checknSetdir()
with open("eye_excercise_log.txt","r") as fi:
lis = fi.readlines()
for i in lis:
print(i)
input("Press to contiue")
except FileNotFoundError:
print("File is not created Yet")
input("Press to contiue")
if __name__ =="__main__":
while True:
logCreater()
答案 0 :(得分:2)
它第一次正确播放音频,但是当它被调用时就无法加载mp3
播放音乐后,通过checknSetdir
在功能os.chdir(target_path)
中更改当前工作目录。
在应用程序的开头获取当前工作目录:
import os
currentWorkDir = os.getcwd()
使用绝对路径加载文件“ Eyesound.mp3” :
pygame.mixer.music.load(os.path.join(currentWorkDir, "Eyesound.mp3"))