DeaD_EyE icon

Play sounds with Pygame ...

DeaD_EyE | PRO | 02/02/24 09:09:26 AM UTC (Edited) | 0 ⭐ | 1322 👁️ | Never ⏰ | []
Python |

920 B

|

None

|

0 👍

/

0 👎

from random import randint
from pathlib import Path
from pygame import mixer
 
 
class Player:
    def __init__(self):
        self.sounds = self._setup()
        self.channel = None
 
    def _setup(self):
        mixer.init()
        return [
            mixer.Sound(file)
            for file in Path(r"C:\Windows\Media").glob("*.wav")
            if file.is_file()
        ]
 
    def __len__(self):
        return len(self.sounds)
 
    def stop(self):
        if self.channel is not None:
            self.channel.stop()
            self.channel = None
 
    def play(self, index):
        if 0 <= index < len(self):
            self.stop()
            self.channel = self.sounds[index]
            self.channel.play()
 
 
def main():
    player = Player()
    while True:
        input("Enter to play a sound ")
        player.play(randint(0, len(player) - 1))
 
 
if __name__ == "__main__":
    main()
 

Comments

  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎