2024-07-06 15:21:14 +02:00
|
|
|
import simpleaudio as sa
|
|
|
|
import wave
|
|
|
|
import base64
|
|
|
|
import os
|
|
|
|
|
|
|
|
# channels OK
|
|
|
|
# bytes per sample OK
|
|
|
|
# sample rate OK
|
|
|
|
|
|
|
|
class handler:
|
2024-07-05 15:27:31 +02:00
|
|
|
def __init__(self):
|
2024-07-06 15:21:14 +02:00
|
|
|
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()
|
2024-07-25 22:17:48 +02:00
|
|
|
self.storage[os.path.basename(target).split(".")[0]] = (frames, channels, bytespersample, frequency)
|
2024-07-06 15:21:14 +02:00
|
|
|
# frames, channels, bytespersample, frequency
|
2024-07-25 22:17:48 +02:00
|
|
|
return os.path.basename(target).split(".")[0]
|
2024-07-06 15:21:14 +02:00
|
|
|
|
|
|
|
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
|
2024-07-05 15:27:31 +02:00
|
|
|
|
2024-07-06 15:21:14 +02:00
|
|
|
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
|
2024-07-05 15:27:31 +02:00
|
|
|
|
2024-07-06 15:21:14 +02:00
|
|
|
def wait(self):
|
|
|
|
if self._playing == False: return
|
|
|
|
self._soundobj.wait_done()
|
|
|
|
self._playing = False
|
2024-07-05 15:27:31 +02:00
|
|
|
|
2024-07-06 15:21:14 +02:00
|
|
|
if __name__ == "__main__":
|
|
|
|
temp = handler()
|
|
|
|
print(temp.loadsound("sounds/joyride.wav"))
|
|
|
|
tsound = temp.getsound("joyride")
|
|
|
|
tsound.play()
|
|
|
|
tsound.wait()
|