如何让其他人(和我自己)能够打开.py文件而不会因使用mp3文件而崩溃?

-1 投票
1 回答
45 浏览
提问于 2025-04-14 17:22

我刚开始学编程,做了一些项目,但这是我第一次在程序中使用除了自动生成的txt文件以外的文件(通过代码中的open...来创建)。

我正在做一个闹钟程序。我有一个mp3文件,用来播放闹钟的声音,我在代码中提供了这个文件的绝对路径。在PyCharm里运行得很好,但当我尝试直接启动这个.py文件时,它就立刻崩溃了。我在默认目录下打开这个文件,那里也有mp3文件,但还是崩溃。

import time
import os
os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = "hide"
import pygame

def set_alarm():
    """Function to set the alarm"""
    while True:
        try:
            print("Set the alarm time:")
            hours = int(input("Enter the hour for the alarm to ring (0-23): "))
            if hours < 0 or hours > 23:  # if hours are below 0 and higher than 23
                print("Invalid hour entered. Please choose between hour 0 and 23.")
            else:  # if hours are between 0 and 23
                while True:  # start another loop
                    try:
                        minutes = int(input("Enter the minutes for the alarm to ring (0-59): "))
                        if minutes < 0 or minutes > 59:  # if minutes are below 0 and higher than 59
                            print("Invalid minute entered. Please choose between minute 0 and 59.")
                        else:  # if minutes are between 0 and 59
                            return hours, minutes  # returns hours and minutes value
                    except ValueError:
                        print("Please enter a number between 0 and 59.")
        except ValueError:
            print("Please enter a number between 0 and 23.")


def check_time():
    """Function to get the current time"""
    current_time = time.localtime()  # current_time variable assigned to the localtime command which retrieves local time
    return current_time.tm_hour, current_time.tm_min  # .tm_hour retrieves current hour and .tm_min retrieves current minute


def trigger_alarm(alarm_name, alarm_message, alarm_sound):
    """Function to trigger the alarm"""
    alarm_sound.play()  # plays the audio file assigned to alarm_sound variable
    print(f"{alarm_name} - {alarm_message} is ringing!")
    while True:
        stop_alarm = input("Press Enter to stop the alarm: ")
        if not stop_alarm:  # if stop_alarm input is empty (Enter is pressed)
            alarm_sound.stop()  # audio file stops playing
            break  # while True loop starts again if condition is not met


def snooze_alarm(alarm_name, alarm_message, alarm_sound):
    """Function to snooze the alarm"""
    while True:
        try:
            snooze = input("Do you want to snooze the alarm? (yes/no): ")
            if snooze.lower() == "yes":
                try:
                    snooze_minutes = int(input("Enter how long to snooze the alarm for (in minutes): "))
                    print(
                        f"Alarm will ring again in {snooze_minutes} minute/s.")  # prints in how many minutes the alarm will ring again (initial input)
                    snooze_length_seconds = snooze_minutes * 60  # snooze_length_seconds variable assigned to the "minutes" (seconds) entered and multiplies it by 60
                    time.sleep(snooze_length_seconds)  # sleeps for that many seconds
                    trigger_alarm(alarm_name, alarm_message, alarm_sound)  # triggers the alarm after the sleep

                except ValueError:
                    print("Please enter a number.")

            else:  # if user inputs anything other than "yes"
                print("You chose not to snooze the alarm.")
                print("=======================")
                break  # break the snooze alarm loop

        except ValueError:
            print("Please choose yes or no.")


def main():
    print("Loading...")
    pygame.mixer.init()  # initializes pygame mixer module

    alarm_sound_path = r"C:\Users\Marko\Documents\python projects\files\mp3\alarm sound.mp3"  # alarm sound location specified, absolute path
    if not os.path.exists(alarm_sound_path):  # if the path does not exist
        print("Alarm sound file not found.")
        return

    alarm_sound = pygame.mixer.Sound(alarm_sound_path)  # alarm sound variable assigned to mp3 file which is played using .Sound
    alarm_hours, alarm_minutes = set_alarm()  # double variable used, one assigned to hour, one assigned to minute, in order of which they are retrieved
    alarm_name = input("Enter the alarm name: ")
    alarm_message = input("Enter the alarm message: ")
    alarm_set = True  # alarm_set set to True indicating that the alarm is enabled initially if set by user
    print(f"Alarm will ring at {alarm_hours}:{alarm_minutes}")
    print("====================================")

    while True:
        current_hour, current_minute = check_time()  # checks time in a while loop (continuously)

        if alarm_set and current_hour == alarm_hours and current_minute == alarm_minutes:  # if the set time is the same as the hours and minute of current time
            trigger_alarm(alarm_name, alarm_message, alarm_sound)  # alarm is triggered
            snooze_alarm(alarm_name, alarm_message,
                         alarm_sound)  # snoozes the alarm if user requests, else skips this line
            alarm_set = False  # disables alarm after triggering

            another_alarm = input("Do you want to set another alarm? (yes/no): ")
            if another_alarm.lower() == "yes":  # if user inputs "yes"
                main()  # calls the main function again
            else:
                print("Exiting.")
                break  # breaks entire code loop

        time.sleep(1)  # checks time every 1 second


if __name__ == "__main__":
    main()
`Traceback (most recent call last): File "C:\Users\Marko\PycharmProjects\alarm_clock\alarm_clock.py", line 4, in <module> import pygame ModuleNotFoundError: No module named 'pygame'`

我不介意把.py文件和mp3文件一起发给你,至少可以先这样,但如果有其他方法可以不这样做,而且不太复杂的话,我也乐意听听。我不想太快接触复杂的东西,喜欢慢慢来,边学边做,但如果需要的话,我也不介意。

我在网上查了一些可以尝试的资源,也试过一些方法,但都没有成功,肯定是我做错了。我看到一些关于base64的内容,但我好像没太理解。如果这是一个可行的选项,请告诉我该怎么做。

1 个回答

0

Python是一种解释型语言。这意味着要运行Python代码,必须先安装Python运行环境和所需的其他库。这就是为什么通常会把Python代码和一个需求文件一起分发的原因。

Pycharm可能在使用一个虚拟环境,这个环境里包含了pygame这个库,而在你默认的Python安装中似乎没有这个库。虚拟环境允许不同的程序有不同的、互不冲突的项目需求。如果你在命令行中加载Pycharm使用的同一个虚拟环境,应该就能正常工作。需要注意的是,Pycharm提供了一个预配置的命令行工具,你可以在开发时使用它。

关于把MP3文件打包在一起,你可以简单地使用相对路径,把它和Python脚本一起分发,或者你可以使用像pyinstaller这样的工具来创建一个包含资源的可执行文件。这种方式的好处是,运行这个程序的人不需要安装Python和你程序所需的库。如果你想更有创意一点,可以把MP3文件编码到Python脚本里,然后在需要的时候写入磁盘,或者在内存中使用

撰写回答