Skip to content
Advertisement

Incrementing count variable without waiting the upper line of code to finish

So,I have this code. I want to increment count variable by not waiting this two audio files to process completely. In my code below it is very obvious that count variable will be incremented only if the two audio files done playing. Is there any idea on playing it on background or can I call a subprocess here ?

import pygame
import time
pygame.mixer.init()
count = 0 
while(True):
    pygame.mixer.Sound('song1.ogg').play()
    time.sleep(0.54)
    pygame.mixer.Sound('song2.ogg').play()
    time.sleep(0.52)
    count +=1
    print(count)

Advertisement

Answer

Actually, the code is waiting for the sleep commands to finish. Generally, you never want to use sleep statements in your main thread, as your program will lock up. You can move the logic for playing sounds to a new Thread.

import time
import pygame
from threading import Thread

def play_sounds():
    pygame.mixer.Sound('song1.ogg').play()
    time.sleep(0.54)
    pygame.mixer.Sound('song2.ogg').play()
    time.sleep(0.52)

pygame.mixer.init()
count = 0 
while(True):
    Thread(target=play_sounds).start()
    count +=1
    print(count)
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement