AudioPlayer.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import logging
  2. import pygame
  3. from core.FileManager import FileManager
  4. class AudioPlayer:
  5. PLAYER_MP3 = "MP3"
  6. PLAYER_WAV = "WAV"
  7. AUDIO_MP3_FREQUENCY = 16000
  8. AUDIO_MP3_SIZE = -16
  9. AUDIO_MP3_CHANNEL = 1
  10. AUDIO_MP3_BUFFER = 2048
  11. AUDIO_DEFAULT_VOLUME = 0.8
  12. def __init__(self, default_type=None, audio_frequency=AUDIO_MP3_FREQUENCY, audio_size=AUDIO_MP3_SIZE, audio_channel=AUDIO_MP3_CHANNEL, audio_buffer=AUDIO_MP3_BUFFER, volume=AUDIO_DEFAULT_VOLUME):
  13. if default_type == self.PLAYER_MP3:
  14. self.audio_frequency = self.AUDIO_MP3_FREQUENCY
  15. self.audio_size = self.AUDIO_MP3_SIZE
  16. self.audio_channel = self.AUDIO_MP3_CHANNEL
  17. self.audio_buffer = self.AUDIO_MP3_BUFFER
  18. else:
  19. self.audio_frequency = audio_frequency
  20. self.audio_size = audio_size
  21. self.audio_channel = audio_channel
  22. self.audio_buffer = audio_buffer
  23. self.volume = volume
  24. pygame.mixer.init(audio_frequency, audio_size, audio_channel, audio_buffer)
  25. def play_audio(self, music_file):
  26. try:
  27. self._init_player_audio(music_file)
  28. logging.debug("Music file %s loaded!", music_file)
  29. except pygame.error:
  30. FileManager.remove_file(music_file)
  31. logging.error("File %s not found! (%s)", music_file, pygame.get_error())
  32. return
  33. self._start_player_audio()
  34. def _init_player_audio(self, music_file):
  35. pygame.mixer.music.set_volume(self.volume)
  36. pygame.mixer.music.load(music_file)
  37. @staticmethod
  38. def _start_player_audio():
  39. logging.info("Starting pygame audio player")
  40. pygame.mixer.music.play()
  41. clock = pygame.time.Clock()
  42. while pygame.mixer.music.get_busy():
  43. clock.tick(20)
  44. return