Advertisement
DeaD_EyE

Play sounds with Pygame ...

Feb 2nd, 2024 (edited)
656
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.92 KB | None | 0 0
  1. from random import randint
  2. from pathlib import Path
  3. from pygame import mixer
  4.  
  5.  
  6. class Player:
  7.     def __init__(self):
  8.         self.sounds = self._setup()
  9.         self.channel = None
  10.  
  11.     def _setup(self):
  12.         mixer.init()
  13.         return [
  14.             mixer.Sound(file)
  15.             for file in Path(r"C:\Windows\Media").glob("*.wav")
  16.             if file.is_file()
  17.         ]
  18.  
  19.     def __len__(self):
  20.         return len(self.sounds)
  21.  
  22.     def stop(self):
  23.         if self.channel is not None:
  24.             self.channel.stop()
  25.             self.channel = None
  26.  
  27.     def play(self, index):
  28.         if 0 <= index < len(self):
  29.             self.stop()
  30.             self.channel = self.sounds[index]
  31.             self.channel.play()
  32.  
  33.  
  34. def main():
  35.     player = Player()
  36.     while True:
  37.         input("Enter to play a sound ")
  38.         player.play(randint(0, len(player) - 1))
  39.  
  40.  
  41. if __name__ == "__main__":
  42.     main()
  43.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement