AudioPlayer.py 1.9 KB

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