Python Forum
Pausing and playing a while loop.
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Pausing and playing a while loop.
#1
Came up with this code for one of three sounds to play when a motion sensor picks something up. I want the ability to pause and play the loop when a key on the keyboard is pressed. I'm really not sure how to implement this.
 


import time
import os
from gpiozero import MotionSensor
import random
import pygame
pygame.init()

pir = MotionSensor(4)
while True:
    if pir.motion_detected:
        print("Motion detected")
        _songs = ('/home/pi/Documents/mp3/1.mp3','/home/pi/Documents/mp3/2.mp3','/home/pi/Documents/mp3/3.mp3')
        _currently_playing_song = None
        def play_a_different_song():
            global _currently_playing_song, _songs
        next_song = random.choice(_songs)
        while next_song == _currently_playing_song:
            next_song = random.choice(_songs)
        _currently_playing_song = next_song
        pygame.mixer.music.load(next_song)
        pygame.mixer.music.play(0)
        time.sleep(10)
        
Thanks,
Liam
Reply
#2
Hello!
Do you asking how to pause the player or the loop? You can just skip the loop if a key is pressed and run it again later. I don't know a way to pause the loop except to check before every condition or funtion call for keystrokes
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Pausing and returning to function? wallgraffiti 1 2,157 Apr-29-2021, 05:30 PM
Last Post: bowlofred
  Slide show with mouse click pausing aantono 1 2,189 Jan-28-2020, 04:25 AM
Last Post: Larz60+
  Pausing a running process? MuntyScruntfundle 2 7,240 Nov-14-2018, 05:14 PM
Last Post: woooee
  Pausing a Script malonn 4 3,811 Aug-04-2018, 07:58 PM
Last Post: malonn
  Pausing a loop with spacebar, resume again with spacebard bigmit37 10 19,880 May-30-2017, 10:28 AM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020