In this article, you will learn how to play sound in Python.
Play Sound in Python
In Python, you can play sound using the pygame library, which is a set of Python modules designed for game development. Here are the steps to play sound in Python using pygame:
Install pygame by running the following command in your terminal or command prompt:
pip install pygame
Import the pygame library in your Python script by adding the following line at the top of your code:
Initialize the pygame library by adding the following code to your script:
Load the sound file:
Load the sound file that you want to play by adding the following code:
sound = pygame.mixer.Sound("path/to/sound/file.wav")
Replace “path/to/sound/file.wav” with the actual path to your sound file.
Play the sound:
Play the sound by adding the following code:
This will play the sound once.
If you want to play the sound repeatedly, you can use the following code instead:
Stop the sound:
To stop the sound, you can use the following code:
Finally, to quit the pygame library, you can use the following code:
Here is an example code that plays a sound file:
import pygame # Initialize pygame pygame.init() # Load the sound file sound = pygame.mixer.Sound("path/to/sound/file.wav") # Play the sound once sound.play() # Wait for the sound to finish pygame.time.wait(int(sound.get_length() * 1000)) # Stop the sound sound.stop() # Quit pygame pygame.quit()