Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
132 views
in Technique[技术] by (71.8m points)

python - pygame.time.set_timer() - 4 2 the floor click

Why doesn't this play my click.wav every 444ms? it just seems to play it at random intervals.

import pygame

pygame.init()
size = (700, 500)
screen = pygame.display.set_mode(size)

pygame.display.set_caption("444ms click")
done = False
clock = pygame.time.Clock()
noise = pygame.mixer.Sound("click.wav")
pygame.time.set_timer(1, 444)

while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
        if event.type == 1:
            noise.play()

    clock.tick(60)

pygame.quit()

and if anyone knows how I could do this more easily that would be good.

Thank You!

@JFSebeastian: Here's the output for the code:

447
436
443
430
449
431
448
432
910
7
407
447
442
432
446
431
448
432
450
432
446
472
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use event.type == pygame.USEREVENT + 1, otherwise the event may be generated for other reasons (whatever 1 event type corresponds to in pygame) that is why it appears random.


The output for the code shows that the time intervals are mostly 440±10 ms with the exception of 910, 7 pair.

±10 milliseconds for a timer sounds normal for fps=60. To get tighter timings, you could use clock.tick() instead of clock.tick(60).

910, 7 pair suggests that set_timer()/tick() might use a time.sleep() analog somewhere. time.sleep() may sleep more than specified that is why the timer may skip a beat. Try clock.tick_busy_loop() that shouldn't sleep and see if you can reproduce the skips.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...