Skip to main content
 首页 » 编程设计

python之如何关闭正在播放的音频文件

2025年05月04日11jillzhang

所以,我最近决定给自己一个简单的项目来测试我的python素养。我创建的是一个闹钟,它会询问某人希望起床的时间,在那个时候,它会播放一个带有 VLC 的 mp3 文件,并且只有在用户回答了一个随机生成的数学问题后才会关闭。问题是,我不知道如何让闹钟停止播放闹钟声。我曾尝试使用 os.popen 发出 killall VLC 命令,但这未能解决问题。

完整代码如下:

#IMPORTS 
import datetime 
import time 
import os 
import sys 
import random 
 
#VARIABLES 
alarm_HH = 00 
alarm_MM = 00 
number_a = random.randrange(0, 999, 2) 
number_b = random.randrange(0, 999, 2) 
command_alarm = 'open -a "VLC" /Users/AlexW/Documents/alarm.mp3' 
command_VLC = 'open -a /Applications/VLC.app' 
command_close = 'killall VLC' 
 
#THE ACTUAL ALARM 
def alarm_function(): 
    #GLOBALS 
    global command_close 
    global command_alarm 
    global alarm_HH 
    global alarm_MM 
    global number_a 
    global number_b 
    while True: 
        now = time.localtime() 
        if now.tm_hour == int(alarm_HH) and now.tm_min == int(alarm_MM): 
            os.popen(command_alarm) 
            print ("---------------") 
            print ("Solve this math problem to disable the alarm") 
            print (number_a) 
            print ("+") 
            print (number_b) 
            print ("---------------") 
            answer = input("Enter Your Answer: ") 
            if answer == number_a + number_b: 
                os.popen(command_close) 
                print ("---------------") 
                print ("Alarm Disabled") 
                alarm_sleep() 
            else: 
                print ("---------------") 
                print("Try again") 
        else: 
            pass 
 
#SET THE TIME FOR THE ALARM 
def alarm_set(): 
    #GLOBALS 
    global command_VLC 
    global alarm_HH 
    global alarm_MM 
    print ("---------------") 
    alarm_HH = input("What hour do you want to wake up? (24 hour format) ") 
    print ("---------------") 
    alarm_MM = input("How about the minute? ") 
    print ("---------------") 
    print ("Opening VLC Player") 
    os.popen(command_VLC) 
    print ("---------------") 
    print ("Alarm Set") 
    print ("---------------") 
    print ("To disable the alarm, quit this program") 
    alarm_function() 
 
#COOLDOWN 
#Used to prevent the alarm from going off twice once the question is completed 
def alarm_sleep(): 
    time.sleep(60) 
    alarm_function() 
 
#STARTING SEQUENCE 
print ("----------------") 
print ("MATH ALARM CLOCK") 
print ("----------------") 
answer = input("Type <<1>> to start ") 
if answer == 1: 
    alarm_set() 
else: 
    alarm_set() 

请您参考如下方法:

问题是你需要在 sudo 权限下执行 kill all 命令。 VLC 没有 native 命令行退出,因此终止是关闭进程的正确方法。