sox.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. # -*- coding: utf-8 -*-
  2. from __future__ import division
  3. from ..__load__ import *
  4. from .base import Base
  5. import subprocess
  6. class Sox(Base):
  7. def __init__(self, **kwargs):
  8. super(self.__class__, self).__init__(**kwargs)
  9. self.playing = False
  10. self.pipe = None
  11. self.delete = False
  12. self.volume = 1
  13. self.onCompleteds = []
  14. def run(self):
  15. cmd = ['play', '-v', str(self.volume), str(self.src)]
  16. cmd = ['aplay', str(self.src)]
  17. self.logger.info(self.mouth.log('播放语音 ' + ' '.join(cmd)))
  18. self.proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  19. self.playing = True
  20. self.proc.wait()
  21. self.playing = False
  22. if self.delete:
  23. File.remove(self.src)
  24. self.logger.info(self.mouth.log('播放完成'))
  25. for onCompleted in self.onCompleteds:
  26. if onCompleted:
  27. onCompleted()
  28. self.onCompleteds = []
  29. def play(self, src, delete=False, onCompleted=None, volume=1):
  30. self.src = src
  31. self.delete = delete
  32. self.onCompleteds.append(onCompleted)
  33. self.volume = volume
  34. self.start()
  35. def appendOnCompleted(self, onCompleted):
  36. if onCompleted:
  37. self.onCompleteds.append(onCompleted)
  38. def play_block(self):
  39. self.run()
  40. def stop(self):
  41. if self.proc:
  42. self.onCompleteds = []
  43. self.proc.terminate()
  44. if self.delete:
  45. File.remove(self.src)
  46. def is_playing(self):
  47. return self.playing