AudioPlayer.py 2.0 KB

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