sound_player.py 994 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import pygame
  2. import time
  3. from client_local.const import game as G
  4. from collections import defaultdict
  5. from datetime import timedelta
  6. try:
  7. pygame.mixer.init()
  8. except Exception as e:
  9. print(e)
  10. PATH = "res/sound"
  11. # 用于记录每种音效的上一次播放时间
  12. last_play_time = defaultdict(lambda: -1)
  13. # 时间间隔阈值(毫秒)
  14. TIME_THRESHOLD = 100
  15. def play(name):
  16. global last_play_time
  17. current_time = pygame.time.get_ticks()
  18. try:
  19. # 检查是否超过时间间隔阈值
  20. if current_time - last_play_time[name] > TIME_THRESHOLD:
  21. sound = pygame.mixer.Sound(f"{PATH}/{name}.wav")
  22. sound.set_volume(G.SOUND_VOLUME)
  23. sound.play()
  24. last_play_time[name] = current_time
  25. except Exception as e:
  26. print(e)
  27. def playWin(name):
  28. try:
  29. sound = pygame.mixer.Sound(f"res/music/{name}.ogg")
  30. sound.set_volume(G.SOUND_VOLUME)
  31. sound.play()
  32. except Exception as e:
  33. print(e)