Created
June 27, 2025 06:13
-
-
Save EncodeTheCode/e341cabf3effbc723c76c23dc5707757 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os, time | |
from pygame._sdl2 import mixer | |
class AudioEngine: | |
Q={'low':(11025,-8,1,512),'medium':(22050,-16,1,1024),'high':(44100,-16,2,2048),'ultra':(48000,-16,2,4096)} | |
def __init__(self, quality='high'): | |
if quality not in self.Q: raise ValueError | |
f=self.Q[quality]; mixer.init(*f) | |
def find_file(self,b,exts): | |
for e in exts: | |
p=f"{b}.{e}" | |
if os.path.exists(p): return p | |
raise FileNotFoundError | |
def play_mp3(self, base, loop=False, vol=1.0): | |
snd=mixer.Sound(self.find_file(base,['mp3'])); snd.set_volume(vol) | |
return snd.play(-1 if loop else 0) | |
def play_wav(self, base, loop=False, vol=1.0): | |
snd=mixer.Sound(self.find_file(base,['wav'])); snd.set_volume(vol) | |
return snd.play(-1 if loop else 0) | |
def stop(self, ch): | |
if ch: ch.stop() | |
def stop_all(self): mixer.stop() | |
def shutdown(self): mixer.quit() | |
# Example | |
if __name__=='__main__': | |
AE=AudioEngine() | |
m1=AE.play_mp3('background_music',True,0.6) | |
m2=AE.play_mp3('ambience',True,0.4) | |
w1=AE.play_wav('click') | |
time.sleep(3); AE.stop(w1) | |
time.sleep(5); AE.stop(m2) | |
time.sleep(5); AE.shutdown() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment