__init__.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. from mods.BaseMod import BaseMod
  4. import threading
  5. import os
  6. import pyaudio
  7. from pydub import AudioSegment
  8. from pydub.utils import make_chunks
  9. import wave
  10. class ModPlaySound(BaseMod):
  11. __isActive=True
  12. def __init__(self):
  13. self._audio = pyaudio.PyAudio()
  14. def IsActive(self):
  15. return True
  16. def __del__(self):
  17. self._audio.terminate()
  18. def onPlaySound(self, soundFile:str, ASync:bool=True):
  19. f = r"ressources/sounds/"+soundFile
  20. if os.path.exists(f):
  21. if ASync:
  22. if soundFile.endswith(".wav"):
  23. threading.Thread(target=self._playSound1, args=(f,), daemon=False).start()
  24. else:
  25. threading.Thread(target=self._playSound3, args=(f,), daemon=False).start()
  26. else:
  27. if soundFile.endswith(".wave"):
  28. self._playSound1(f)
  29. else:
  30. self._playSound3(f)
  31. else:
  32. print(f"File not found: {f}")
  33. def _playSound1(self, path):
  34. f = wave.open(path,"rb")
  35. stream = self._audio.open(format = self._audio.get_format_from_width(f.getsampwidth()),channels = f.getnchannels(),rate = f.getframerate(),output = True)
  36. data = f.readframes(1024)
  37. while data:
  38. stream.write(data)
  39. data = f.readframes(1024)
  40. stream.stop_stream()
  41. stream.close()
  42. def _playSound2(self, path):
  43. playsound(path)
  44. def _playSound3(self, path):
  45. sound = AudioSegment.from_file(path)
  46. stream = self._audio.open(format = self._audio.get_format_from_width(sound.sample_width),
  47. channels = sound.channels,
  48. rate = sound.frame_rate,
  49. output = True)
  50. start = 0
  51. length = sound.duration_seconds
  52. volume = 100.0
  53. playchunk = sound[start*1000.0:(start+length)*1000.0] - (60 - (60 * (volume/100.0)))
  54. millisecondchunk = 50 / 1000.0
  55. self.time = start
  56. for chunks in make_chunks(playchunk, millisecondchunk*1000):
  57. self.time += millisecondchunk
  58. stream.write(chunks._data)
  59. if self.time >= start+length:
  60. break
  61. stream.close()