wav.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. # -*- coding: utf-8 -*-
  2. from __future__ import division
  3. from ..__load__ import *
  4. from .base import Base
  5. class Wav(Base):
  6. def __init__(self, **kwargs):
  7. super(self.__class__, self).__init__(**kwargs)
  8. self.playing = False
  9. self.stop = False
  10. def run(self):
  11. # play a voice
  12. CHUNK = 1024
  13. self.logger.info(self.mouth.log('播放语音 %s', self.src))
  14. f = wave.open(self.src, "rb")
  15. with no_alsa_error():
  16. audio = pyaudio.PyAudio()
  17. stream = audio.open(
  18. format=audio.get_format_from_width(f.getsampwidth()),
  19. channels=f.getnchannels(),
  20. rate=f.getframerate(),
  21. input=False,
  22. output=True)
  23. self.playing = True
  24. stream.start_stream()
  25. data = f.readframes(CHUNK)
  26. while data != '' and not self.stop:
  27. stream.write(data)
  28. data = f.readframes(CHUNK)
  29. print('data=="": {}, self.stop: {}'.format(data == '', self.stop))
  30. self.playing = False
  31. stream.stop_stream()
  32. stream.close()
  33. audio.terminate()
  34. if self.onCompleteds:
  35. for onCompleted in self.onCompleteds:
  36. if onCompleted:
  37. onCompleted()
  38. def play(self, src, onCompleted=None):
  39. self.src = src
  40. self.onCompleted = onCompleted
  41. self.start()
  42. def play_block(self):
  43. self.run()
  44. def stop(self):
  45. self.stop = True
  46. File.remove(self.src)
  47. def is_playing(self):
  48. return self.playing