#!/usr/bin/env python # -*- coding: utf-8 -*- from mods.BaseMod import BaseMod import threading import os import pyaudio from pydub import AudioSegment from pydub.utils import make_chunks import wave class ModPlaySound(BaseMod): __isActive=True def __init__(self): self._audio = pyaudio.PyAudio() def __del__(self): self._audio.terminate() def onPlaySound(self, soundFile:str, ASync:bool=True): f = r"ressources/sounds/"+soundFile if os.path.exists(f): if ASync: if soundFile.endswith(".wav"): threading.Thread(target=self._playSound1, args=(f,), daemon=False).start() else: threading.Thread(target=self._playSound3, args=(f,), daemon=False).start() else: if soundFile.endswith(".wave"): self._playSound1(f) else: self._playSound3(f) else: print(f"File not found: {f}") def _playSound1(self, path): f = wave.open(path,"rb") stream = self._audio.open(format = self._audio.get_format_from_width(f.getsampwidth()),channels = f.getnchannels(),rate = f.getframerate(),output = True) data = f.readframes(1024) while data: stream.write(data) data = f.readframes(1024) stream.stop_stream() stream.close() def _playSound2(self, path): playsound(path) def _playSound3(self, path): sound = AudioSegment.from_file(path) stream = self._audio.open(format = self._audio.get_format_from_width(sound.sample_width), channels = sound.channels, rate = sound.frame_rate, output = True) start = 0 length = sound.duration_seconds volume = 100.0 playchunk = sound[start*1000.0:(start+length)*1000.0] - (60 - (60 * (volume/100.0))) millisecondchunk = 50 / 1000.0 self.time = start for chunks in make_chunks(playchunk, millisecondchunk*1000): self.time += millisecondchunk stream.write(chunks._data) if self.time >= start+length: break stream.close()