Hi I want to play a mp3 but when the function recalled that is logCreater an error shows can load mp3.First time it play audio correctly but when it's recalled then it cant load mp3.Error msg say's pygame.mixer.music.load cant load xxxxx.mp3 file Actually this is lil project and this is just one module of it.Please suggest me the code correction.
错误信息是:
回溯(最近一次调用)。 文件 "e:\Tutorials etc\ProjBack/Healthy_programmer_cli/MainModule.py",第151行,在timCount() 文件 "e:\Tutorials etc\ProjBack/Healthy_programmer_cli/MainModule. py", 第65行, in timCount EyeExcercise.logCreater() File "e:tutorials etc/ProjBack/Healthy_programmer_cli/EyeExcercise.py", 第45行, in logCreater 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()
第一次正确播放音频,但当它被调用时,它不能加载MP3。
播放音乐后,在功能中改变当前的工作目录。checknSetdir
,由 os.chdir(target_path)
.
在应用程序开始时获取当前工作目录。
import os
currentWorkDir = os.getcwd()
使用绝对路径加载文件 "眼睛的声音.mp3":
pygame.mixer.music.load(os.path.join(currentWorkDir, "Eyesound.mp3"))