需要帮助让我的Python脚本循环一个视频不止一次时,运动检测

ozxc1zmp  于 2023-06-07  发布在  Python
关注(0)|答案(1)|浏览(184)

我有一个在我的Rasberry Pi上运行的Python脚本,它使用VLC和PIR运动传感器。
我希望它循环一个名为lop.mp4的视频,直到检测到运动,此时它播放mot.mp4 ...一旦该视频结束,其返回到循环lop.mp4,直到检测到运动。
目前,我有它的工作,除了它播放motidermp4的第一次检测到运动,但不会再这样做之后。我需要一点帮助,确保它不止一次这样做。

import gpiozero
import vlc
import time
import threading

# create a button that uses GPIO4
pir_sensor = gpiozero.MotionSensor(4)

# create vlc instance
player = vlc.Instance()

# create media player
media_player = player.media_player_new()

def play_video(path):
    media = player.media_new(path)
    media_player.set_media(media)
    media_player.play()
    # wait a bit for the player to start, then set fullscreen
    time.sleep(0.1)
    media_player.set_fullscreen(False)

def play_default_video_loop():
    play_video('/home/pi/elf/lop.mp4')
    while True:
        if media_player.get_state() == vlc.State.Ended:
            play_video('/home/pi/elf/lop.mp4')
        time.sleep(0.1)

def on_motion():
    print("Motion detected!")
    play_video('/home/pi/elf/mot.mp4')
    while media_player.get_state() != vlc.State.Ended:
        time.sleep(0.1)  # wait for video to finish
    play_default_video_loop()  # restart default video loop

pir_sensor.when_motion = on_motion

# start playing default video in a new thread
threading.Thread(target=play_default_video_loop).start()

try:
    while True:
        time.sleep(1)
except KeyboardInterrupt:
    print("Exiting")

media_player.stop()

我需要lop.mp4循环时,没有运动和mot.mp4播放时,有运动,目前我只能得到mot.mp4工作的第一次检测运动。

xu3bshqb

xu3bshqb1#

试试这个

import gpiozero
import vlc
import time
import RPi.GPIO as GPIO
flag = 1
# create a button that uses GPIO4
pir_sensor = 4
GPIO.setwarnings(False) 
GPIO.setmode(GPIO.BCM)
GPIO.setup(pir_sensor, GPIO.IN)
# create vlc instance
player = vlc.Instance()

# create media player
media_player = vlc.MediaPlayer(player)

def play_video(path):
    media_player.set_media(vlc.Media(path))
    media_player.play()

def on_motion():
    media_player.set_media(vlc.Media('/home/pi/elf/mot.mp4'))
    media_player.play()
    # global flag
    # flag=0
    while media_player.get_state() != vlc.State.Ended:
        time.sleep(0.0001)  # wait for video to finish
    # flag =1
   
p_input_flag = 0
def edge_detect(input_flag):
    global p_input_flag
    output = 0
    if(input_flag  and (not p_input_flag)):
        output = 1
    p_input_flag = input_flag
    return output
try:
    play_video('/home/pi/elf/lop.mp4')
    while True:
        # if flag:
        if(edge_detect(GPIO.input(pir_sensor) == True)):
            on_motion()
        if media_player.get_state() == vlc.State.Ended:
            play_video('/home/pi/elf/lop.mp4')  # restart default video loop
            
        time.sleep(0.0001)
except KeyboardInterrupt:
    print("Exiting")

media_player.stop()

相关问题