не можете непрерывно воспроизводить mp3 файлы внутри al oop, используя pygame? - PullRequest
2 голосов
/ 22 апреля 2020

Привет, я хочу воспроизвести mp3, но при вызове функции logCreater появляется сообщение об ошибке, которое может загрузить mp3. В первый раз он воспроизводит звук правильно, но когда он вызывается, он не может загрузить mp3. ошибка msg, скажем, pygame.mixer.musi c .load не может загрузить файл xxxxx.mp3 На самом деле это проект lil, и это всего лишь один из его модулей. Пожалуйста, предложите мне исправление кода.

Сообщение об ошибке:

Трассировка (последний вызов был последним): файл "e: \ Tutorials etc \ ProjBack \ Healthy_programmer_cli \ MainModule.py", строка 151 , в файле timCount () "e: \ Tutorials etc \ ProjBack \ Healthy_programmer_cli \ MainModule.py", строка 65, в файле timCount EyeExcercise.logCreater (), файл "e: \ Tutorials etc \ ProjBack \ Healthy_programmer_cli \ EyeExcercise.py", строка 45, в logCreater pygame.mixer.musi c .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()

1 Ответ

1 голос
/ 22 апреля 2020

Первый раз, когда он воспроизводит аудио правильно, но когда он вызывается, он не может загрузить mp3

После воспроизведения музыки c текущий рабочий каталог изменяется в функции checknSetdir , os.chdir(target_path).

Получить текущий рабочий каталог в начале приложения:

import os

currentWorkDir = os.getcwd()

Использовать абсолютный путь для загрузки файла "Eyesound.mp3" :

pygame.mixer.music.load(os.path.join(currentWorkDir, "Eyesound.mp3"))
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...