AudioPlayer.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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_MP3_44100_FREQUENCY = 44100
  14. AUDIO_DEFAULT_VOLUME = 0.8
  15. def __init__(self, volume=AUDIO_DEFAULT_VOLUME):
  16. self.volume = volume
  17. def init_play(self, default_type=None, audio_frequency=AUDIO_MP3_FREQUENCY, audio_size=AUDIO_MP3_SIZE, audio_channel=AUDIO_MP3_CHANNEL,
  18. audio_buffer=AUDIO_MP3_BUFFER):
  19. if default_type == self.PLAYER_MP3 or default_type == self.PLAYER_MP3:
  20. audio_size = self.AUDIO_MP3_SIZE
  21. audio_channel = self.AUDIO_MP3_CHANNEL
  22. audio_buffer = self.AUDIO_MP3_BUFFER
  23. else:
  24. audio_size = audio_size
  25. audio_channel = audio_channel
  26. audio_buffer = audio_buffer
  27. audio_frequency = audio_frequency
  28. pygame.mixer.init(audio_frequency, audio_size, audio_channel, audio_buffer)
  29. def play_audio(self, music_file):
  30. try:
  31. self._init_player_audio(music_file)
  32. logger.debug("Music file %s loaded!", music_file)
  33. except pygame.error:
  34. FileManager.remove_file(music_file)
  35. logger.error("File %s not found! (%s)", music_file, pygame.get_error())
  36. return
  37. self._start_player_audio()
  38. def _init_player_audio(self, music_file):
  39. pygame.mixer.music.set_volume(self.volume)
  40. pygame.mixer.music.load(music_file)
  41. @staticmethod
  42. def _start_player_audio():
  43. clock = pygame.time.Clock()
  44. clock.tick(100)
  45. logger.debug("Starting pygame audio player")
  46. pygame.mixer.music.play()
  47. while pygame.mixer.music.get_busy():
  48. clock.tick(20)
  49. return