2014-10-03 159 views
2

因此,我最近决定给自己一个简单的项目来测试我的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() 

回答

1

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

+0

我试过了,它仍然不起作用。 “command_close ='sudo killall VLC'” – Alex 2014-10-03 03:49:15

+1

可以su su root并重新运行脚本而不使用sudo并查看它是否有效?我不确定close命令中的sudo是否提示输入密码。 – TheoretiCAL 2014-10-03 04:17:34