因此,我最近决定给自己一个简单的项目来测试我的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没有退出本地命令行,因此杀死是关闭进程的正确方法。

关于python - 如何关闭正在播放的音频文件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26172796/

10-16 16:22