import simpleaudio as sa import wave import base64 import os # channels OK # bytes per sample OK # sample rate OK class handler: def __init__(self): self.storage = {} def loadfromstring(self, target): # decode frames from b64 frames = base64.b64decode(target[1]) # rebuild tuple temp = (frames, target[2], target[3], target[4]) self.storage[target[0]] = temp def loadsound(self, target): if target == None: return with wave.open(target, 'r') as fd: frames = fd.readframes(-1) channels = fd.getnchannels() bytespersample = fd.getsampwidth() frequency = fd.getframerate() self.storage[os.path.basename(target).split(".")[0]] = (frames, channels, bytespersample, frequency) # frames, channels, bytespersample, frequency return os.path.basename(target).split(".")[0] def getsound(self, target): if not target in self.storage: raise ValueError(f"Sound {target} not loaded!") else: return sound(self.storage[target]) def tostring(self, target): if not target in self.storage: raise ValueError(f"Sound {target} not loaded!") data = self.storage[target] # encode frames to b64 frames = str(base64.b64encode(data[0]), "ascii", "ignore") # rebuild tuple out = (target, frames, data[1], data[2], data[3]) # name, frames, channels, bytespersample, frequency return out class sound: def __init__(self, data): self.frames = data[0] self.channels = data[1] self.bps = data[2] self.freq = data[3] self._playing = False self._soundobj = None def play(self): if self._playing == True and self._soundobj.is_playing(): return self._soundobj = sa.play_buffer(self.frames, self.channels, self.bps, self.freq) self._playing = True def stop(self): if self._playing == False: return self._soundobj.stop() self._playing = False def wait(self): if self._playing == False: return self._soundobj.wait_done() self._playing = False if __name__ == "__main__": temp = handler() print(temp.loadsound("sounds/joyride.wav")) tsound = temp.getsound("joyride") tsound.play() tsound.wait()