AudioPlayer.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import logging
  2. import pygame
  3. import os
  4. class AudioPlayer:
  5. AUDIO_FREQUENCY = 16000
  6. AUDIO_SIZE = -16
  7. AUDIO_CHANNEL = 1
  8. AUDIO_BUFFER = 2048
  9. @classmethod
  10. def play_audio(cls, music_file, volume=0.8, keep_file=False):
  11. try:
  12. cls._init_player_audio(music_file, volume)
  13. logging.debug("Music file %s loaded!", music_file)
  14. except pygame.error:
  15. cls._remove_file(music_file)
  16. logging.error("File %s not found! (%s)", music_file, pygame.get_error())
  17. return
  18. cls._start_player_audio()
  19. if not keep_file:
  20. cls._remove_file(music_file)
  21. @classmethod
  22. def _init_player_audio(cls, music_file, volume):
  23. pygame.mixer.init(cls.AUDIO_FREQUENCY, cls.AUDIO_SIZE, cls.AUDIO_CHANNEL, cls.AUDIO_BUFFER)
  24. pygame.mixer.music.set_volume(volume)
  25. pygame.mixer.music.load(music_file)
  26. @staticmethod
  27. def _start_player_audio():
  28. logging.info("Starting pygame audio player")
  29. pygame.mixer.music.play()
  30. clock = pygame.time.Clock()
  31. while pygame.mixer.music.get_busy():
  32. clock.tick(10)
  33. return
  34. @staticmethod
  35. def _remove_file(file_path):
  36. if os.path.exists(file_path):
  37. return os.remove(file_path)