__init__.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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 __del__(self):
  15. self._audio.terminate()
  16. def onPlaySound(self, soundFile:str, ASync:bool=True):
  17. f = r"ressources/sounds/"+soundFile
  18. if os.path.exists(f):
  19. if ASync:
  20. if soundFile.endswith(".wav"):
  21. threading.Thread(target=self._playSound1, args=(f,), daemon=False).start()
  22. else:
  23. threading.Thread(target=self._playSound3, args=(f,), daemon=False).start()
  24. else:
  25. if soundFile.endswith(".wave"):
  26. self._playSound1(f)
  27. else:
  28. self._playSound3(f)
  29. else:
  30. print(f"File not found: {f}")
  31. def _playSound1(self, path):
  32. f = wave.open(path,"rb")
  33. stream = self._audio.open(format = self._audio.get_format_from_width(f.getsampwidth()),channels = f.getnchannels(),rate = f.getframerate(),output = True)
  34. data = f.readframes(1024)
  35. while data:
  36. stream.write(data)
  37. data = f.readframes(1024)
  38. stream.stop_stream()
  39. stream.close()
  40. def _playSound2(self, path):
  41. playsound(path)
  42. def _playSound3(self, path):
  43. sound = AudioSegment.from_file(path)
  44. stream = self._audio.open(format = self._audio.get_format_from_width(sound.sample_width),
  45. channels = sound.channels,
  46. rate = sound.frame_rate,
  47. output = True)
  48. start = 0
  49. length = sound.duration_seconds
  50. volume = 100.0
  51. playchunk = sound[start*1000.0:(start+length)*1000.0] - (60 - (60 * (volume/100.0)))
  52. millisecondchunk = 50 / 1000.0
  53. self.time = start
  54. for chunks in make_chunks(playchunk, millisecondchunk*1000):
  55. self.time += millisecondchunk
  56. stream.write(chunks._data)
  57. if self.time >= start+length:
  58. break
  59. stream.close()