- 1 year ago
How to play sound using Python
To play sound using Python, you can utilize the winsound
module on Windows or the pygame
library for cross-platform sound playback. Here's how you can use each of them:
- Using
winsound
module (Windows-only):
pythonimport winsound
# Play a system sound
winsound.PlaySound("path_to_sound_file.wav", winsound.SND_FILENAME)
Make sure to replace "path_to_sound_file.wav"
with the actual path to the sound file you want to play. You can also use system sound aliases like winsound.MB_ICONASTERISK
for playing system alert sounds.
- Using
pygame
library (cross-platform):
pythonimport pygame
# Initialize the pygame mixer
pygame.mixer.init()
# Load the sound file
sound = pygame.mixer.Sound("path_to_sound_file.wav")
# Play the sound
sound.play()
You'll need to install the pygame
library before using it. You can install it using pip
:
pip install pygame
Again, replace "path_to_sound_file.wav"
with the actual path to the sound file you want to play.
Both methods provide basic sound playback capabilities. The pygame
library offers more advanced features for sound manipulation, such as adjusting volume, looping, and fading.
Choose the method that suits your needs based on your operating system and the specific requirements of your sound playback task.