pyaudioplayer.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. # -*- coding: utf-8 -*-
  2. import logging
  3. import wave
  4. import pyaudio
  5. from kalliope.PlayerModule import PlayerModule
  6. logging.basicConfig()
  7. logger = logging.getLogger("kalliope")
  8. CHUNK = 1024
  9. class Pyaudioplayer(PlayerModule):
  10. """
  11. This Class is representing the Player Object used to play the all sound of the system.
  12. """
  13. def __init__(self, **kwargs):
  14. super(Pyaudioplayer, self).__init__(**kwargs)
  15. logger.debug("[Pyaudioplayer.__init__] instance")
  16. logger.debug("[Pyaudioplayer.__init__] args : %s " % str(kwargs))
  17. def play(self, file_path):
  18. """
  19. Play the sound located in the provided file_path
  20. :param file_path: The file path of the sound to play. Must be wav format
  21. :type file_path: str
  22. """
  23. if self.convert:
  24. self.convert_mp3_to_wav(file_path_mp3=file_path)
  25. # open the wave file
  26. wf = wave.open(file_path, 'rb')
  27. # instantiate PyAudio
  28. p = pyaudio.PyAudio()
  29. # open stream (2)
  30. stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
  31. channels=wf.getnchannels(),
  32. rate=wf.getframerate(),
  33. # frames_per_buffer=CHUNK,
  34. output=True)
  35. # read data
  36. data = wf.readframes(CHUNK)
  37. logger.debug("Pyplayer file: %s" % str(file_path))
  38. # play stream (3)
  39. while len(data) > 0:
  40. stream.write(data)
  41. data = wf.readframes(CHUNK)
  42. # stop stream (4)
  43. stream.stop_stream()
  44. stream.close()
  45. # close PyAudio
  46. p.terminate()