Here are two versions of the code, one using pygame.time.set_timer() and the other using pygame.time.delay():
Version 1: Using pygame.time.set_timer():
import pygame
import time
import random
class Metronome:
def __init__(self):
self.pause_flag = False
def play_metronome(self):
pygame.init()
pygame.mixer.init()
time_since_last_bpm_change = time.perf_counter()
self.bpm = random.randint(30, 150)
print(self.bpm)
interval = int(60 / self.bpm * 1000)
pygame.mixer.music.load("I:/metronome.mp3")
METRONOME_EVENT = pygame.USEREVENT + 1
pygame.time.set_timer(METRONOME_EVENT, interval)
while True:
for event in pygame.event.get():
if event.type == METRONOME_EVENT:
if not self.pause_flag:
pygame.mixer.music.play()
elapsed_time = time.perf_counter() - time_since_last_bpm_change
if elapsed_time > 6:
pygame.mixer.music.stop()
self.bpm = random.randint(30, 150)
print(self.bpm)
interval = int(60 / self.bpm * 1000)
time_since_last_bpm_change = time.perf_counter()
pygame.time.set_timer(METRONOME_EVENT, interval)
Version 2: Using pygame.time.delay():
import pygame
import time
import random
class Metronome:
def __init__(self):
self.pause_flag = False
def play_metronome(self):
pygame.init()
pygame.mixer.init()
time_since_last_bpm_change = time.perf_counter()
self.bpm = random.randint(30, 150)
print(self.bpm)
interval = int(60 / self.bpm * 1000)
pygame.mixer.music.load("I:/metronome.mp3")
while True:
if not self.pause_flag:
pygame.mixer.music.play()
pygame.time.delay(interval)
elapsed_time = time.perf_counter() - time_since_last_bpm_change
if elapsed_time > 6:
pygame.mixer.music.stop()
self.bpm = random.randint(30, 150)
print(self.bpm)
interval = int(60 / self.bpm * 1000)
time_since_last_bpm_change = time.perf_counter()
Pros and Cons:
pygame.time.set_timer():
- Pros:
- Allows for more accurate timing and flexibility.
- Non-blocking, allowing other events to be processed while waiting for the timer.
- Cons:
- More complex to implement, as it requires event handling.
pygame.time.delay():
- Pros:
- Cons:
- Blocks other events from being processed during the specified delay.
- Less accurate timing compared to
pygame.time.set_timer().